[Solved] infinite loop c++ with while and vector of pairs [closed]


One way to track down the problem without stepping through the debugger is to write values of the key data in important lines.

Also, since you know that you have an infinite loop, add code to limit the number of times the loop gets executed.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//ADDED: Function to print the contents of the vector.
void print(vector <pair<unsigned long long, unsigned long long > > const& v)
{
   for (auto const& p : v )
   {
      cout << p.first << " " << p.second << " ";
   }
   cout << endl;
}

int main()
{
   unsigned long long T,N , M ,p , m ;
   vector <pair<unsigned long long, unsigned long long > > v;
   cin>>T ;
   for  (unsigned long long i=0 ; i<T;i++)
   {
      v={};
      cin>>N>>M ;
      for (unsigned long long j=0 ; j< N ; j++)
      {
         cin>>p>>m ;
         v.push_back({p,m});
      }
      sort(v.begin(),v.end());

      //ADDED: Limit the number iterations of the loop.
      int count = 0;
      while (M>=v[0].second && count < 20)
      {
         //ADDED: Print the key pieces that control the loop.
         cout << "M: " << M << " v[0].second: " << v[0].second << endl;

         while (v[0].first<=v[1].first)
         {
            v[0].first+=1 ;
            M-=v[0].second;

         }
         sort(v.begin(),v.end());

         //ADDED: Print the vector
         print(v);
         ++count;
      }
   }
   cout<<"ans"<<v[0].first ;
}

Here’s the output given your input:

M: 7 v[0].second: 2
2 3 3 1 3 2 
M: 3 v[0].second: 3
3 1 3 2 4 3 
M: 18446744073709551613 v[0].second: 1
3 2 4 1 4 3 
M: 18446744073709551612 v[0].second: 2
4 1 4 3 5 2 
M: 18446744073709551608 v[0].second: 1
4 3 5 1 5 2 
M: 18446744073709551607 v[0].second: 3
5 1 5 2 6 3 
M: 18446744073709551601 v[0].second: 1
5 2 6 1 6 3 
M: 18446744073709551600 v[0].second: 2
6 1 6 3 7 2 
M: 18446744073709551596 v[0].second: 1
6 3 7 1 7 2 
M: 18446744073709551595 v[0].second: 3
7 1 7 2 8 3 
M: 18446744073709551589 v[0].second: 1
7 2 8 1 8 3 
M: 18446744073709551588 v[0].second: 2
8 1 8 3 9 2 
M: 18446744073709551584 v[0].second: 1
8 3 9 1 9 2 
M: 18446744073709551583 v[0].second: 3
9 1 9 2 10 3 
M: 18446744073709551577 v[0].second: 1
9 2 10 1 10 3 
M: 18446744073709551576 v[0].second: 2
10 1 10 3 11 2 
M: 18446744073709551572 v[0].second: 1
10 3 11 1 11 2 
M: 18446744073709551571 v[0].second: 3
11 1 11 2 12 3 
M: 18446744073709551565 v[0].second: 1
11 2 12 1 12 3 
M: 18446744073709551564 v[0].second: 2
12 1 12 3 13 2 
ans12

As you can see, the value of M becomes very large. That happens when (M -
v[0].second)
is a negative value.

You can fix it by making M a signed type. Whether that is the appropriate solution for you is difficult to tell from your post. I trust that you will be able to resolve the issue one way or another.

4

solved infinite loop c++ with while and vector of pairs [closed]