上手发现与01背包仅差一个组合购买,于是愉快并查集+01背包
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 using namespace std; 5 6 int father[20001],c[20001],w[20001],f[20001]; 7 int n,m,k,x,y; 8 9 int find(int x) 10 { 11 return x==father[x]?x:father[x]=find(father[x]); 12 } 13 14 int main() 15 { 16 scanf("%d%d%d",&n,&m,&k); 17 for (int i=1;i<=n;i++) 18 { 19 scanf("%d%d",&w[i],&c[i]); 20 father[i]=i; //初始化 21 } 22 for (int i=1;i<=m;i++) 23 { 24 scanf("%d%d",&x,&y); 25 if (find(x)!=find(y)) father[find(y)]=find(x); 26 } 27 for (int i=1;i<=n;i++) 28 if (father[i]!=i) 29 { 30 c[find(i)]+=c[i]; 31 w[find(i)]+=w[i]; 32 c[i]=w[i]=0; 33 } 34 for (int i=1;i<=n;i++) 35 for (int j=k;j>=w[i];j--) 36 f[j]=max(f[j],f[j-w[i]]+c[i]); 37 printf("%d\n",f[k]); 38 return 0; 39 }