Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9524 | Accepted: 3378 |
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 首先,如果最后形成的是一个图,那么这样一定是矛盾的, 所以最后形成的图应该是一棵树, 所以即是最大生成树#include <map> #include <set> #include <stack> #include <queue> #include <cmath> #include <ctime> #include <vector> #include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; #define INF 0x3f3f3f3f #define inf -0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define mem0(a) memset(a,0,sizeof(a)) #define mem1(a) memset(a,-1,sizeof(a)) #define mem(a, b) memset(a, b, sizeof(a)) typedef long long ll; const int MAXN=21000;//最大点数 const int MAXM=51000;//最大边数 int f[MAXN]; struct Edge{ int from,to,dis; }e[MAXM]; int tot;//边数,加边前初始化为0 void addedge(int u,int v,int w){ e[tot].from=u; e[tot].to=v; e[tot++].dis=w; } bool cmp(Edge a,Edge b){ return a.dis>b.dis; } int find(int x){ int k, j, r; r = x; while(r != f[r]) //查找跟节点 r = f[r]; //找到跟节点,用r记录下 k = x; while(k != r){ //非递归路径压缩操作 j = f[k]; //用j暂存parent[k]的父节点 f[k] = r; //f[x]指向跟节点 k = j; //k移到父节点 } return r; //返回根节点的值 } void init(int n){ for(int i=1;i<=n;i++) f[i]=i; tot=0; } int main(){ int t,n,m,k; scanf("%d",&t); while(t--){ scanf("%d%d%d",&n,&m,&k); init(n+m); int u,v,w; for(int i=1;i<=k;i++){ scanf("%d%d%d",&u,&v,&w); u++,v++; addedge(u,n+v,w); } sort(e,e+tot,cmp); int cnt=0;//计算加入的边数 int ans=0; for(int i=0;i<tot;i++){ u=e[i].from,v=e[i].to,w=e[i].dis; int t1=find(u); int t2=find(v); if(t1!=t2){ ans+=w; f[t1]=t2; cnt++; } } printf("%d\n",(n+m)*10000-ans); } return 0; }