题意:要招募n个男兵和m个女兵,而每招募一个人都要花费10000,这可是笔大开销,还好,可以用男女之间的关系减少费用,因为当招募一个士兵时,如果已招的人里与其有t点关系,则只需10000-n的费用。
给出r对关系,求出最少费用。
分析:当招募b时,若用了b与a 的关系,则在a和b之间连一条边,很明显,当全部招募后,会连出一个森林,这个森林的总权值就是最多可以减少的费用,用10000*(n+m)将这个费用减去,就是所求结果。
无向图的最大权森林问题可以把边的权值取反后用最小生成树解决。
代码如下:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const double eps = 1e-8;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const int M=20010;
const int N=50010;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
typedef pair<int, int> pii;
int n,m,r,f[N];
struct edge
{
int x,y,w;
}e[N];
bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int Find(int x)
{
return x==f[x]?x:(f[x]=Find(f[x]));
}
int kruskal()
{
int i=0,j=0,sum=0;
sort(e,e+r,cmp);
while(i<n+m-1) {
if (j>=r) break; // 因为是森林,所以不一定连通
edge t=e[j++];
int a=Find(t.x),b=Find(t.y);
if (a!=b){
f[b]=a;
sum+=t.w;
i++;
}
}
return sum;
}
void slove()
{
int i,j;
scanf("%d%d%d",&n,&m,&r);
for (i=0;i<r;i++) { scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].w); e[i].y+=n; e[i].w=-e[i].w; } // 因为男兵和女兵的编号都是从0开始,因此将女兵的编号加上n,结点总数就为n+m个
for (i=0;i<=n+m;f[i]=i++);
printf("%d\n",10000*(n+m)+kruskal());
}
int main()
{
int i,j,t;
while(~scanf("%d",&t))
{
while(t--)
{
slove();
}
}
}