1387:搭配购买(buy)
并查集+01背包。
#include<iostream>
#include<string>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=10005;
int n , m , cost;
int f[N];
int w[N] , v[N] , kk[N];//01背包求解时候用
struct sta{
int x , y;
}k[N];
int find(int v){
return f[v]==v?v:f[v]=find(f[v]);
}
void merge(int u , int v){
int t1 = find(u);
int t2 = find(v);
if(t1 != t2){
f[t2]=t1;
k[t1].x+=k[t2].x;
k[t1].y+=k[t2].y;
}
}
int main(){
cin>>n>>m>>cost;
for(int i=1;i<=n;i++)f[i]=i;
for(int i = 1 ; i <= n ; i++){
scanf("%d%d",&k[i].x,&k[i].y);
}
int x , y;
for(int i = 1 ; i <= m ; i++){
scanf("%d%d",&x,&y);
merge(x , y);//合并要搭配的商品
}
int cnt=0;
for(int i=1;i<=n;i++)
if(f[i]==i){
w[++cnt]=k[i].x;
v[cnt]=k[i].y;
}
for(int i=1;i<=cnt;i++){
for(int j=cost;j>=w[i];j--){
if(j>=w[i])kk[j]=max(kk[j],v[i]+kk[j-w[i]]);
}
}
cout<<kk[cost];
}