Reputation: 1291
I'm practicing Longest Increasing Sequence problem and I was using this code:
int lis(vector<int>& a)
{
int s = a.size();
vector<int> prev(s);
vector< vector<int> > pile;
int m = -1; // lis size
for(int i=0; i<s; i++)
{
// initialize piles
vector<int> vt;
pile.push_back(vt);
}
pile[0].push_back(0); // a[0] must go to the first pile
prev[0] = -1;
for(int i=1; i<s; i++)
{
cout << "i: " << i << endl;
for(int j=0; j<s; j++)
{
cout << "j: " << j << endl;
if(pile[j].size() == 0)
{
printf("pile %d is empty, push %d (%d)\n", j, i, a[i]);
pile[j].push_back(i);
if(j == 0)
{
prev[i] = -1;
}
else
{
prev[i] = pile[j-1].back();
}
m = max(j, m);
break;
}
else if(a[pile[j].back()] < a[i])
{
printf("go to pile %d\n", j+1);
continue;
}
else
{
printf("push %d (%d) to pile %d\n", i, a[i], j);
pile[j].push_back(i);
if(j == 0)
{
prev[i] = -1;
}
else
{
prev[i] = pile[j-1].back();
}
m = max(j, m);
break;
}
}
}
// print out the sequences
int ind = pile[m][0];
vector<int> res;
while(ind != -1)
{
res.push_back(a[ind]);
ind = prev[ind];
}
for(int i=res.size()-1; i>=0; i--)
{
cout << res[i] << " ";
}
return m+1; // return lis size
}
Which was, working fine. Then, I wanted to simplify the code and came up with this:
int lis(vector<int>& a)
{
/* same */
for(int i=1; i<s; i++)
{
cout << "i: " << i << endl;
for(int j=0; j<s; j++)
{
cout << "j: " << j << endl;
if(a[pile[j].back()] > a[i] || pile[j].size() == 0)
{
printf("push %d to pile %d\n", a[i], j);
pile[j].push_back(i);
prev[i] = (j == 0) ? -1 : pile[j-1].back();
m = max(j, m);
break;
}
printf("go to pile %d\n", j+1);
}
}
/* same */
}
With this code, when it goes to the next pile (j
increases), the program suddenly exits. (Process returned 0xC0000005
)
This couldn't be buffer overflow or segmentation fault because every vector/array is declared correctly and the index isn't exceeding the bound.
This also couldn't be memory leak or dangling pointer because I didn't use any manual allocation.
I couldn't sort this out!
What did I do wrong?
Upvotes: 1
Views: 240
Reputation: 6206
To begin with, in the following statement:
if(a[pile[j].back()] > a[i] || pile[j].size() == 0)
I believe that you should check the second part of the expression first.
In other words, check pile[j].size() == 0
first, in order to avoid calling pile[j].back()
if true.
Upvotes: 1