Reputation: 31
I'm a new programmer, I was solving a problem at codeforces when I got this error.
http://codeforces.com/contest/342/problem/A
My algorithm works fine but I don't know why at the very end, I have an error message and a return value different from 0. It's shown in the picture below.
https://i.sstatic.net/sz9Jc.png
Thank you in advance !!
Here is my algorithm:
#include <iostream>
#include <vector>
using namespace std;
void print(int a, int b, int c, int n) {
for (int i=0;i<n;++i) cout<<a<<" "<<b<<" "<<c<<endl;
}
int main () {
int n; cin>>n;
vector<int> V(5);
bool cont=true;
for (int i=0;i<n;++i) {
V[i]=0;
}
for (int i=0;i<n;++i) {
int a; cin>>a;
if (a==5 || a==7) cont=false;
if (cont==true) {
if (a==1) V[0]++;
if (a==2) V[1]++;
if (a==3) V[2]++;
if (a==4) V[3]++;
if (a==6) V[4]++;
}
}
if (cont==false) {
cout<<-1<<endl;
}else {
if (V[0]==V[1] && V[1]==V[3] && V[2]==0 && V[4]==0) {
print(1,2,4,V[0]);
}else if (V[0]==V[1] && V[1]==V[4] && V[2]==0 && V[3]==0) {
print(1,2,6,V[0]);
}else if (V[0]==V[2] && V[2]==V[4] && V[1]==0 && V[3]==0) {
print(1,3,6,V[0]);
}else if (V[0]==V[1] && V[1]==(V[4]+V[3]) && V[2]==0) {
print(1,2,4,V[3]);
print(1,2,6,V[4]);
} else if (V[0]==V[4] && V[0]==(V[1]+V[2]) && V[3]==0) {
print(1,2,6,V[1]);
print(1,3,6,V[2]);
} else if (V[0]==(V[1]+V[2]) && V[0]==(V[3]+V[4]) && V[3]==V[1]) {
print(1,2,4,V[1]);
print(1,3,6,V[2]);
} else if (V[0]==(V[1]+V[2]) && V[0]==(V[4]+V[3]) && V[3]==(V[1]/2) && V[2]==(V[4]/2)){
print(1,2,4,V[3]);
print(1,2,6,V[1]-V[3]);
print(1,3,6,V[2]);
} else {
cout<<-1<<endl;
}
}
cout<<"fin"<<endl;
return 0;
}
Upvotes: 2
Views: 4111
Reputation: 4557
Your vector is to small for the example you show:
vector<int> V(5);
after that line you clean the vector
for (int i=0;i<n;++i) {
V[i]=0;
}
but in your example you need nine elements. You corrupt the heap with that. Change the first line to
vector<int> V(n);
and it will return the expected 0.
Upvotes: 2
Reputation: 3934
for (int i=0;i<n;++i) {
V[i]=0;
}
You should check that n
is 5 or less. Or allocate the vector dynamically.
In case of n>5
you are causing heap corruption, which results in the exit code you got.
If you use the value of n
for something else and you just wanted to init your vector you can iterate
for (int i=0;i<5;++i)
Upvotes: 3
Reputation: 3348
The exit code that you see, 3221226356, converted to hex is 0xC0000374. Googling for that indicates that it is the exception code for heap corruption. You've got an error somewhere on cleanup and an exception is thrown, then that exception code has emerged as your process exit code.
Upvotes: 1