0

So i am doing a graph coloring problem in which i input number of test cases for which the code has to run. Here's the code:

#include <bits/stdc++.h>
using namespace std;


int main() {
    int test,num,i,j,k,l,sum,num1,num2,count,col;
    cin>>test;
    for(i=0;i<test;i++){
        sum = 0;
        cin>>num;
        int arr[num][num];

        for(j=0;j<num;j++){
            for(k=0;k<num;k++){
                arr[j][k] = 0;
            }
        }

        for(l=0;l<num-1;l++){
            cin>>num1>>num2;
            arr[num1-1][num2-1] = 1;
            arr[num2-1][num1-1] = 1;
        }

        int* colVert = new int[num];

        for(j=0;j<num;j++){
            colVert[j] = 0;
        }

        for(j=0;j<num;j++){
            count = 0;
            l=0;
            if(j == 0){
                colVert[j] = 1;
            }

            else{
                for(k=0;k<num;k++){
                    if(arr[j][k] == 1){
                        count++;
                    }
                }
                int colSeq[count];
                for(k=0;k<num;k++){
                    if(arr[j][k] == 1){
                        colSeq[l] = colVert[k];
                        l++;
                    }
                }
                sort(colSeq, colSeq+count);
                /*for(k=0;k<count;k++){
                    cout<<colSeq[k];
                }*/
                for(k=0;k<count;k++){
                    if(colSeq[k] != k+1){
                        col = k;
                        break;
                    }
                    else{
                        col = colSeq[k] + 1;
                    }
                }
                colVert[j] = col;
            }
        }

        for(i=0;i<num;i++){
            sum = sum + colVert[i];
        }

        cout<<sum<<endl;
    }
    return 0;
}

So the problem is the code only runs for the first test case and then program ends. I think the problem is with the way i have declared colVert array. So how to do it correctly so that it runs for every case?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 3
    Use `std::vector`? – P.P Nov 06 '19 at 21:53
  • Unrelated: `#include ` [loads the gun](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). `using namespace std;` [takes the safety off](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). Be really cautious with this combination. – user4581301 Nov 06 '19 at 21:59

1 Answers1

0

Guys the issue was resolved. The problem was not in the way how colVert array was declared but a really silly mistake:

for(i=0;i<num;i++){
            sum = sum + colVert[i];
        }

I used 'i' variable in a loop inside a loop which is also using 'i' as its counter. Simply using any other counter variable fixed the problem.