Reputation: 20669
While I was solving a question from codeforces(link to the question: https://codeforces.com/contest/1466/problem/A) I encountered weird output from the below code
#include<iostream>
#include<vector>
#include<set>
using namespace std;
void solve(){
int64_t n;
cin>>n;
if (n<2){
cout<<0<<endl;
return;
}
vector<int64_t> vec(n, 0);
for(auto &i: vec){
cin>>i;
}
set<int64_t> s;
for(int64_t i=0; i<n-1; ++i){
for(int64_t j=i+1; j<n; ++j){
s.insert(vec[j]-vec[i]);
}
}
cout<<s.size()<<endl;
}
int main(){
int64_t t;
cin>>t;
while(t--){
solve();
}
return 0;
}
Input:
8
4
1 2 4 5
3
1 3 5
3
2 6 8
2
1 2
1
50
5
3 4 5 6 8
3
1 25 26
6
1 2 4 8 16 32
Ouptut given by my code:
4
2
3
1
0
53
1
1
When I removed if block it passed all the pretests/testcases.
if (n<2){
cout<<0<<endl;
return;
}
Expected output:
4
2
3
1
0
5
3
15
After removing the if block I get the same output as above. I'm not able to understand how if block is affecting the size of set in the next iteration.
Compiled with g++
same output with -std=c++11
-std=c++14
and -std=c++17
Upvotes: 0
Views: 60
Reputation: 15446
if (n<2){
cout<<0<<endl;
return;
}
Since you're returning here, it means that if n
is 1, you never read that one value out of std::cin
.
If you remove that if, then that one value will get read in here:
vector<int64_t> vec(n, 0);
for(auto &i: vec){
cin>>i;
}
So if you want the if to work as expected, it should be:
if (n<2){
cout<<0<<endl;
if(n == 1) { std::cin >> n; } // remove 1 item from stream
return;
}
Upvotes: 2