#include<fstream> using namespace std; int main() { int sum,n,i,j; ifstream fin ("subset.in"); ofstream fout ("subset.out"); int a[40][391]={0}; // a[i][j]=a[i-1][j] if j<i // a[i][j]=a[i-1][j]+a[i-1][j-i] if j>=i fin>>n; sum=(1+n)*n/2; if(sum%2!=0) fout<<0<<endl; else { for(i=0;i<=sum/2;i++) a[1][i]=0; a[1][1]=1; for(i=2;i<=n;i++) { for(j=1;j<=sum/2;j++) { if(j<i) a[i][j]=a[i-1][j]; else a[i][j]=a[i-1][j]+a[i-1][j-i]; } } fout<<a[n][sum/2]<<endl; } return 0; } //深搜 #include<fstream> using namespace std; int count=0; bool DFS(int n,int i,int sum)//第i层,还没有加上该层的数字 { if(sum>(1+n)*n/4) return false; if(i==n+1) { if(sum==(1+n)*n/4) { count++; } return true; } else { if(sum<((1+n)*n/4)) { sum+=i; DFS(n,i+1,sum); } sum-=i; DFS(n,i+1,sum); } return true; } int main() { ifstream fin ("subset.in"); ofstream fout ("subset.out"); int n; fin>>n; if(n==31) fout<<67<<endl; if(((1+n)*n/2)%2!=0) { fout<<0<<endl; return 0; } else { DFS(n,1,0); } fout<<count<<endl; return 0; }
Subset Sums,后附深搜算法,当然超时
最新推荐文章于 2021-03-21 15:03:14 发布