简体   繁体   中英

Why doesn't this break statement work as intended?

I have this simple snippet of code with a break statement. I was trying to solve this http://codeforces.com/contest/787/problem/B . I came up with this solution:

public static void main(String[] args) {
    FastReader in = new FastReader();
    int n = in.nextInt(), m = in.nextInt();
    HashSet<Integer> set = new HashSet<>();
    for(int i=0;i<m;i++){
        set.clear();
        int k = in.nextInt();
        boolean cancel = true;
        for(int j=0;j<k;j++){
            int cur = in.nextInt();
            if(set.contains(-cur)){
                cancel = false;
                break;
            }
            else set.add(cur);
        }
        if(cancel && k!=0){
            System.out.println("YES");
            return;
        }
    }
    System.out.println("NO");
}

It didn't pass the tests, but the moment I remove the break statement after the cancel = false; line. It works. I can't seem to explain what the different between having the break statement so that when the first time you found -cur inside set you would change cancel to false then break and just assign false to cancel everytime you find -cur inside set and wait till the loop end and not break.

When you break out of for(int j=0;j<k;j++) , you don't read all the k numbers of that line of input (unless you were already at the last number).

For example, consider this input:

2 2
3 -1 1 -2
1 2

After having read -1 and 1, you program sets cancel to false and breaks out of the inner loop. Next time through the outer loop it will read -2 into k , and you've got it messed up.

When you remove the break statement, you are reading all the numbers correctly, and your program therefore works correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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