Description
Windy has a country, and he wants to build an army to protect his country. He has picked up N girls and M boys and wants to collect them to be his soldiers. To collect a soldier without any privilege, he must pay 10000 RMB. There are some relationships between girls and boys and Windy can use these relationships to reduce his cost. If girl x and boy y have a relationship d and one of them has been collected, Windy can collect the other one with 10000-d RMB. Now given all the relationships between girls and boys, your assignment is to find the least amount of money Windy has to pay. Notice that only one relationship can be used when collecting one soldier.
Input
The first line of input is the number of test case.
The first line of each test case contains three integers, N, M and R.
Then R lines followed, each contains three integers xi, yi and di.
There is a blank line before each test case.
1 ≤ N, M ≤ 10000
0 ≤ R ≤ 50,000
0 ≤ xi < N
0 ≤ yi < M
0 < di < 10000
Output
Sample Input
2 5 5 8 4 3 6831 1 3 4583 0 0 6592 0 1 3063 3 3 4975 1 3 2049 4 2 2104 2 2 781 5 5 10 2 4 9820 3 2 6236 3 1 8864 2 4 8326 2 0 5156 2 0 1463 4 1 2439 0 4 4373 3 4 8889 2 4 3133
Sample Output
71071
54223
这道题从某种意义上来说是一道模板题,只要是kruskal算法和并查集的运用,题意就是给一片森林,来生成个最大生成树,其实吧权值变成负的就成了最小生成树,这道题的代码理解后就可以知道kruskal的基本代码以及细节。不说了,直接上代码,我只按照模板敲了一遍,一次就过了,也是醉人。。。
AC代码:
/
// // //
// Created by Team 3 //
// Copyright (c) 2015年 Team 3. All rights reserved. //
/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <set>
#include <vector>
#define INF 1<<31
#define cir(i,a,b) for (int i=a;i<=b;i++)
#define CIR(j,a,b) for (int j=a;j>=b;j--)
#define CLR(x) memset(x,0,sizeof(x))
typedef long long ll;
using namespace std;
#define maxn 55000
int N,M; //N girls M boys
long long R; //R个关系;
int x[maxn],y[maxn],d[maxn];
int par[maxn],rank[maxn];
struct Edge
{
int u,v,cost;
}e[maxn];
void init(int n) //初始化
{
for (int i=0;i<=n;i++)
{
par[i]=i;
rank[i]=0;
}
}
int find(int x) //寻找父亲节点
{
if (par[x]==x) return x;
else return par[x]=find(par[x]);
}
bool same(int x,int y) //判断是否在同一集合
{
return find(x)==find(y);
}
bool cmp(const Edge &a,const Edge &b) //比较函数,用于sort排序
{
return a.cost <b.cost;
}
void unite(int x,int y)
{
x=find(x);y=find(y);
if (x==y) return ;
if (rank[x]<rank[y]) par[x]=y;
else
{
par[y]=x;
if (rank[x]==rank[y])
rank[x]++;
}
}
int kruskal()
{
sort(e+1,e+1+R,cmp);
init(N+M);
int res=0;
for (long long i=1;i<=R;i++)
{
Edge es=e[i];
if (!same(es.u,es.v))
{
unite(es.u,es.v);
res+=es.cost;
}
}
return res;
}
int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d%d%lld",&N,&M,&R);
for (long long i=1;i<=R;i++)
{
scanf("%d%d%d",&x[i],&y[i],&d[i]);
e[i]=(Edge){x[i],N+y[i],-d[i]};
}
cout << 10000*(M+N)+kruskal() << endl;
}
return 0;
}