Conscription POJ - 3723

题目本身不难,但好像题意有点难懂。

给了N个男生,M个女生。要招募这(N+M)个人,需要花费1000*(N+M)。但现在男生和女生直接可以有一种联系,这种联系的数值为di,如果你想招募x,并且y与x 相连同时y已经被招募(其实即使y没有被招募,你也可以选择先花10000招募y,然后y就变成被招募状态了),那么你可以减少di元。

因此,我们可以将招募的人统一用并查集合并,如果某条边的两个点x,y,不在同一集合时,代表这条边的值可以被减少。

所以,最佳的做法就是每次选择权重最大的边,即用最小生成树的算法来做。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
using namespace std;
const int maxn=1e5+7;
#define INF 0x3f3f3f3f
typedef pair<int,int> P;
int M,N,R;
int ans;
int f[maxn];
struct Point
{
    int u,v,cost;
    Point(int u_,int v_,int c)
    {
        u = u_;
        v = v_;
        cost = c;
    }
    Point(){

    }
};
Point edge[maxn];
bool cmp(Point a,Point b)
{
    return a.cost<b.cost;
}
void init(int n)
{
    for(int i=0;i<n;i++)
    {
        f[i] = i;
    }
}
int Find(int x)
{
    if(f[x]==x) return f[x];
    else return f[x]=Find(f[x]);
}
bool same(int x,int y)
{
    return Find(x)==Find(y);
}
void com(int x,int y)
{
    int fx =Find(x),fy = Find(y);
    if(fx==fy) return;
    f[fy] = fx;
}
void krustal()
{
    sort(edge,edge+R,cmp);
    init(N+M);
    ans=0;
    for(int i=0;i<R;i++)
    {
        int x=edge[i].u,y=edge[i].v;
        //cout<<x<<" "<<y<<endl;
        if(same(x,y)==0)
        {
            ans+=edge[i].cost;
            com(x,y);
        }
    }
}
int T;
int x[maxn],y[maxn],d[maxn];
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    cin>>T;
    while(T--)
    {
        cin>>N>>M>>R;
        //cout<<N<<" "<<M<<" "<<R<<endl;
        for(int i=0;i<R;i++)
        {
            scanf("%d%d%d",&x[i],&y[i],&d[i]);
        }
        for(int i=0;i<R;i++)
        {
            edge[i].u=x[i];
            edge[i].v=y[i]+N;
            edge[i].cost = -d[i];
        }
        krustal();
        cout<<10000*(N+M)+ans<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值