思路: 最小生成树算法统计绝对值最大权重和
#include <stdio.h>
#include <map>
#include <algorithm>
using namespace std;
int tree[20010];
int num_boy, num_girl, num_cost;
struct link
{
int ID_boy;
int ID_girl;
int cost;
};
link l[50050];
bool cmp(const link &fomar, const link &later)
{
return fomar.cost < later.cost;
}
void init()
{
for (int i = 0; i < num_boy+num_girl; ++i)
{
tree[i] = i;
}
}
int root(int i)
{
if(i == tree[i])
return i;
return tree[i] = root(tree[i]);
}
int same(int a, int b)
{
if(root(a) == root(b))
return 1;
return 0;
}
void connect(int a, int b)
{
int root_a = root(a);
int root_b = root(b);
tree[root_a] = root_b;
}
int mintree()
{
init();
int diff = 0;
sort(l, l+num_cost, cmp);
for (int i = 0; i < num_cost; ++i)
{
int now_boy = l[i].ID_boy;
int now_girl = l[i].ID_girl;
int now_cost = l[i].cost;
if(same(now_boy, now_girl))
continue;
diff += now_cost;
connect(now_boy, now_girl);
}
return diff;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d %d %d", &num_boy, &num_girl, &num_cost);
int res = (num_boy+num_girl)*10000;
for (int i = 0; i < num_cost; ++i)
{
int temp_boy, temp_girl, temp_cost;
scanf("%d %d %d", &temp_boy, &temp_girl, &temp_cost);
l[i].ID_boy = temp_boy;
l[i].ID_girl = temp_girl+num_boy;
l[i].cost = -temp_cost;
}
printf("%d\n", res + mintree());
}
}