简体   繁体   English

如何每次都在不同大小的循环中重新声明相同的数组?

[英]How to redeclare the same array again in a loop with different size everytime?

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.我认为问题在于我声明 colVert 数组的方式。 So how to do it correctly so that it runs for every case?那么如何正确地做到这一点,以便它适用于每种情况呢?

Guys the issue was resolved.伙计们,问题已经解决了。 The problem was not in the way how colVert array was declared but a really silly mistake:问题不在于 colVert 数组的声明方式,而是一个非常愚蠢的错误:

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.我在循环内的循环中使用了“i”变量,该循环也使用“i”作为其计数器。 Simply using any other counter variable fixed the problem.只需使用任何其他计数器变量即可解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM