[英]Why doesn't this break statement work as intended?
I have this simple snippet of code with a break statement. 我有一个带有break语句的简单代码段。 I was trying to solve this http://codeforces.com/contest/787/problem/B . 我正在尝试解决此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; 它没有通过测试,但是在cancel = false之后,我删除了break语句。 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. 我似乎无法解释具有break语句的区别,因此,当您第一次发现-cur内部集合时,您将cancel更改为false,然后中断,并在每次在set内部找到-cur时分配false来取消并等待直到循环结束而不中断。
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(int j=0;j<k;j++)
,您不会读取该输入行的所有k
数字(除非您已经在最后一个数字上)。
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. 读取-1和1之后,您可以将cancel
设置为false
并跳出内部循环。 Next time through the outer loop it will read -2 into k
, and you've got it messed up. 下次通过外循环,它会将-2读入k
,您将其弄乱了。
When you remove the break
statement, you are reading all the numbers correctly, and your program therefore works correctly. 当您删除break
语句时,您正在正确读取所有数字,因此您的程序可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.