Luo Gu P1455 with purchase

Hit the jump meaning of problem-solving


Solution: This question is to see the beginning, I thought it was like a budget Jinming of the same tree backpack dp, but closer examination reveals their different, This question sets out to buy an item other

Related items must buy, then think carefully, with this relationship, primary and accessories do not become an item of the same thing, so we maintain a disjoint-set look at the relationship, then there will be relations

Items combined into one item can do 01 backpack.

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 #define maxn 10005
 6 
 7 using namespace std;
 8 
 9 int f[maxn],c[maxn],w[maxn];
10 int n,vmax,m;
11 int dp[maxn];
12 
13 inline int find(int k)
14 {
15     if(f[k]==k) return f[k];
16     return f[k]=find(f[k]);
17 }
18 
19 int main()
20 {
21     scanf("%d%d%d",&n,&m,&vmax);
22     for(int i=1;i<=n;i++)
23         f[i]=i;
24     for(int i=1;i<=n;i++)
25         scanf("%d%d",&w[i],&c[i]);
26     for(int i=1;i<=m;i++)
27     {
28         int x,y;
29         scanf("%d%d",&x,&y);;
30         int f1=find(x);
31         int f2=find(y);
32         f[f1]=f2;
33     }
34     for(int i=1;i<=n;i++)
35     {
36         int f1=find(i);
37         if(f1!=i)
38         {
39             c[f1]+=c[i];
40             w[f1]+=w[i];
41             c[i]=w[i]=0;
42         }
43     }
44     for(int i=1;i<=n;i++)
45         for(int v=vmax;v>=w[i];v--)
46             dp[v]=max(dp[v],dp[v-w[i]]+c[i]);
47     printf("%d",dp[vmax]);
48     return 0;
49 } 
P1455

 

Guess you like

Origin www.cnblogs.com/Hoyoak/p/11371877.html