Buy with Match Time limit: Ms Memory limit: 65536 KB Number of submissions: 268 by number: 117 "Title description"Joe thought the clouds were beautiful and decided to go to the shops in the mountains to buy some clouds. There are n clouds in the store, the clouds are numbered as 1,2,......,n, and each cloud has a value. But the store owner told him that some clouds should be paired to buy, so buying a cloud would have to be bought with a cloud that matches the cloud. But Joe has a limited amount of money, so he wants to buy the more value the better. Input Line 1th n,m,w, means n cloud, M collocation, Joe has W's money. Line 2~n+1, each line of Ci,di represents the price and value of I cloud. Line N+2~n+1+m, each line of Ui,vi, said buy the UI must buy VI, similarly, if buy vi must buy UI. Output A row that represents the maximum value that can be obtained. "Input Sample" 5 3
3,
3 3,
5,
1
1 3 3 2 4 2 "output Example" 1 "Hint""Data Range" 30% Data Guarantee: n≤100 50% Data Guarantee: n≤1,000;m≤100;w≤1,000 100% Data Guarantee: n≤10,000;0≤m≤5000;w≤10,000 The first task of "algorithmic analysis" is to group these clouds together and then treat the set as a whole, and the 01 backpack is Ouke.
"Code Analysis"
#include <bits/stdc++.h> using namespace std;
#define N 10100 int fa[n],c[n],d[n],v[n],w[n];
int find (int x) {return x==fa[x]?x:fa[x]=find (fa[x]);} int main () {int n,m,w1;
scanf ("%d%d%d", &N,&M,&W1);
for (int i=1;i<=n;i++) {fa[i]=i;
scanf ("%d%d", &c[i],&d[i]);
} for (int i=1;i<=m;i++) {int x, y;
scanf ("%d%d", &x,&y);
int R1=find (x), R2=find (y); if (R1!=R2) {fa[r1]=r2;//is purchased together with the same set}} for (int i=1;i<=n;i++) {int X=find (i
);
W[x]+=c[i];
v[x]+=d[i];//the total cost of the same set is calculated} int tot=0;
for (int i=1;i<=n;i++) {if (fa[i]==i)//One of the collection root nodes is only one, so the root node is a set of clouds {W[++tot]=w[i];
V[tot]=v[i];
}} int f[n];
memset (F,0,sizeof (f));
for (int i=1;i<=tot;i++)//01 backpack for (int j=w1;j>=w[i];j--) F[j]=max (F[j],f[j-w[i]]+v[i]);
printf ("%d", f[w1]);
return 0;
} This code is a little bit confused, later study: #include <bits/stdc++.h> using namespace std; #define N 10100 int fa[n],c[n],d[n]; int find (int x) {
Return X==fa[x]?x:fa[x]=find (Fa[x]);
} int main () {int n,m,w;
scanf ("%d%d%d", &n,&m,&w);
for (int i=1;i<=n;i++) {fa[i]=i;
scanf ("%d%d", &c[i],&d[i]);
} for (int i=1;i<=m;i++) {int x, y;
scanf ("%d%d", &x,&y);
int R1=find (x), R2=find (y);
if (R1!=R2) {fa[r2]=r1;//Why not F[R1]=R2 c[r1]+=c[r2];//cumulatively calculates the total price of each collection D[R1]+=D[R2];
}} int tot=0;
for (int i=1;i<=n;i++) {cout<<fa[i]<< "" <<c[i]<< "" <<d[i]<<endl;;
if (fa[i]==i) {c[++tot]=c[i];
D[tot]=d[i];
}} int f[n];
memset (F,0,sizeof (f));
for (int. i=1;i<=tot;i++) for (int j=w;j>=c[i];j--) F[j]=max (F[j],f[j-c[i]]+d[i]);
printf ("%d", f[w]);
return 0; }
|