我正在这个在线评判网站(http://zerojudge.tw/ShowProblem?problemid=a981#)处理这个问题。对不起,它只用普通话:(。基本上它是一个子集的问题。 继续在我的提交中收到相同的错误消息:
RE(SIGSEGV)
分段错误
我的C代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int w[35]= {0};
bool is_included[35]= {false};
bool is_promising(int);
void sum_of_subsets(int,int,int);
int n = 0,W = 0,weight = 0,total = 0,i = 0,j = 0,k = 0,flag = 0,temp = 0;
int main(int argc,char* argv[]) {
while(scanf("%d %d",&n,&W)==2) {
memset(w,0,sizeof(w));
memset(is_included,false,sizeof(is_included));
total = 0;
i = 1;
temp = n;
while(temp--) {
scanf("%d",&w[i++]);
}
//ascending bubble sort
for(j = n; j >= 1; --j) {
flag=0;
for(k = 1; k < j; ++k) {
if(w[k]>w[k+1]) {
temp = w[k];
w[k] = w[k+1];
w[k+1] = temp;
flag=1;
}
}
if(!flag) {
break;
}
}
for(i=1; i<=n; ++i) {
total+=w[i];
}
sum_of_subsets(0,0,total);
}
return 0;
}
bool is_promising(int index) {
return (weight+total>=W)&&(weight==W||weight+w[index+1]<=W);
}
void sum_of_subsets(int index,int weight,int total) {
int j=1;
if(is_promising(index)) {
if(weight==W) {
for(j=1; j<=index; ++j) {
if(is_included[j]) {
printf("w[%d] = %d\n",j,w[j]);
}
}
} else {
//include w[index+1]
is_included[index+1]=true;
sum_of_subsets(index+1,weight+w[index+1],total-w[index+1]);
//exclude w[index+1]
is_included[index+1]=false;
sum_of_subsets(index+1,weight,total-w[index+1]);
}
}
}
感谢您的任何建议。