2 条题解

  • 1
    @ 2022-12-14 11:41:41
    #include<bits/stdc++.h>
    using namespace std;
    int n,m,w;
    int father[1000005],val[1000005],rmb[1000005];
    int dp[10000005];
    int getfather(int u)
    {
    	if(father[u]==u)return u; 
    	father[u]=getfather(father[u]);
    	return father[u];
    }
    void unio(int x,int y)
    {
    	int fx=getfather(x);
    	int fy=getfather(y);
    	if(fx!=fy)
    	{
    		father[fx]=fy;
    		rmb[fy]+=rmb[fx];
    		val[fy]+=val[fx];
    	}
    }
    int main()
    {
    	int i,j;
    	cin>>n>>m>>w;
    	for(i=1;i<=n;i++)
    	{
    		father[i]=i;
    		cin>>rmb[i]>>val[i];
    	}
    	for(i=1;i<=m;i++)
    	{
    		int x,y;
    		cin>>x>>y;
    		unio(x,y);
    	}
        for(i=1;i<=n;i++)
    	if(father[i]==i)
    	for(j=w;j>=rmb[i];j--)dp[j]=max(dp[j],dp[j-rmb[i]]+val[i]);
    	cout<<dp[w];
    	return 0;
    }
    
    • 0
      @ 2023-5-20 8:29:37

      并查集

      #include <iostream>
      #include <stack>
      #include <cmath>
      #include <vector>
      #include <string.h>
      #include <queue>
      #include <stdio.h>
      #include <iomanip>
      #include <cstdio>
      #include <algorithm>
      #define int long long
      #define double long double
      using namespace std;
      const int N = 1e5 + 10;
      const int INF = 0x3f3f3f3f;
      int n, m, wi;
      int w[N], v[N], fa[N], dp[N];
      int find(int x)
      {
      	return fa[x] == x ? x : fa[x] = find(fa[x]);
      }
      void init()
      {
      	for(int i = 1; i <= n; i++)
      	{
      		fa[i] = i;
      	}
      }
      signed main()
      {
      	cin >> n >> m >> wi;
      	init();
      	for(int i = 1; i <= n; i++)
      	{
      		cin >> w[i] >> v[i];
      	}
      	int x, y;
      	while(m--)
      	{
      		cin >> x >> y;
      		int xx = find(x);
      		int yy = find(y);
      		fa[xx] = yy;
      	}
      	for(int i = 1; i <= n; i++)
      	{
      		if(fa[i] != i)
      		{
      			int ii = find(i);
      			v[ii] += v[i];
      			v[i] = 0;
      			w[ii] += w[i];
      			w[i] = 0;
      		}
      	}
      	for(int i = 1; i <= n; i++)
      	{
      		for(int j = wi; j >= w[i]; j--)
      		{
      			dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
      		}
      	}
      	cout << dp[wi] << endl;
      	return 0;
      }
      
      • 1

      信息

      ID
      36
      时间
      1000ms
      内存
      128MiB
      难度
      5
      标签
      递交数
      7
      已通过
      6
      上传者