I'm having problem with vector, (in the usage of push_back) but it only appears when using additional g++ flag -O2 (I need it).
#include <cstdio>
#include <开发者_如何学Govector>
typedef std::vector<int> node;
typedef std::vector<node> graph;
int main()
{
int n, k, a, b, sum;
bool c;
graph g(n, node());
c = scanf("%i%i", &n, &k);
for(int i=0; i<n; i++)
{
sum=2;
for(int j=0; j<i; j++)
sum*=2;
for(int j=0; j<sum; j++)
{
if(j%2==0)
c = scanf("%i", &a);
else
{
c = scanf("%i", &b);
a += b;
g[i].push_back(a); //---------------LINE WHICH CAUSES SEGMENTATION FAULT
}
}
}
for(int i=n-2; i>=0; i--)
{
for(size_t j=0; j<g[i].size(); j++)
{
if(g[i+1][(j*2)] >= g[i+1][(j*2)+1])
g[i][j] = g[i+1][j*2];
else
g[i][j] = g[i+1][(j*2)+1];
}
}
printf("%i\n", g[0][0]);
return 0;
}
I think you have:
graph g(n, node());
c = scanf("%i%i", &n, &k);
in the reverse order. As it stands, the variable 'n' which you use to size graph is not initialised.
Initializing the vector with n
before the input operation means you're invoking the dreaded Undefined Behavior. As stated here, the program is allowed to do anything after that.
Works perfectly if you initialize n
as I already mentioned in my comment. Change the first lines to:
int n, k, a, b, sum;
int c;
c = scanf("%i%i", &n, &k); // initialize n *first*
if(c != 2) return -1; // scanf does not return bool but the number of parsed arguments
graph g(n, node());
精彩评论