http://acm.hdu.edu.cn/showproblem.php?pid=1171
我错在这里把
int c1[max];
int c2[max];
int value[51];
int count[51];
放在main函数里面,结果导致stack overflow 栈溢出,但放在main函数外面作为全局变量就不会。这是因为函数的内存在开在栈上的,全局变量内存在堆上分配。前者远小于后者
View Code
1 #include<cstdio> 2 #include<cstring> 3 4 #define max 250010 5 6 int c1[max]; 7 int c2[max]; 8 int value[51]; 9 int count[51]; 10 11 int main( ) 12 { 13 int i; 14 int j; 15 int k; 16 int sum; 17 int n; 18 int len; 19 20 while( scanf("%d",&n)==1&&(n>0)) 21 { 22 23 memset(value,0,sizeof(value)); 24 memset(count,0,sizeof(count)); 25 sum = 0; 26 27 for( i = 1; i <= n; i++ ) 28 { 29 scanf("%d %d",&value[i],&count[i]); 30 sum += value[i]*count[i]; 31 } 32 33 memset(c1,0,sum*sizeof(c1[1])); 34 memset(c2,0,sum*sizeof(c1[1])); 35 36 for( i = 0; i <= value[1]*count[1]; i += value[1] ) //此处赋初值要注意 37 { 38 c1[i] = 1; 39 } 40 41 len = count[1]*value[1]; 42 43 for( j = 2; j <= n; j++ ) //指向表达式 44 { 45 for( i = 0 ; i <= len; i++ ) //指向已经求了的表达式中每项 46 for( k = 0; k <= value[j]*count[j]; k += value[j] ) 47 c2[i+k] += c1[i]; 48 len += count[j]*value[j]; 49 for( k = 0; k <= len; k++ ) //更新表达式系数 50 { 51 c1[k] = c2[k]; 52 c2[k] = 0; 53 } 54 } 55 for( j = sum/2; j >= 0; j-- ) 56 { 57 58 if( c1[j] != 0 ) 59 { 60 printf("%d %d\n",sum-j,j ) ; 61 break; 62 } 63 } 64 65 } 66 return 0; 67 }