征兵问题,本质就是最小生成树。
题源来自《挑战程序竞赛》第二版 109页
//
// 109_Conscription.cpp
// changlle
//
// Created by user on 1/3/16.
// Copyright (c) 2016 user. All rights reserved.
//
#include <iostream>
#include <vector>
#include <queue>
#include<functional>
using namespace std;
int N = 5, M = 5;
int R = 8;
int par[20];
int rankv[20];
void init(int n)
{
for (int i = 0; i < n; i++)
{
par[i] = i;
rankv[i] = 0;
}
}
int find(int x)
{
if (par[x] == x)
{
return x;
}
else
{
return par[x] = find(par[x]);
}
}
void unite(int x, int y)
{
x = find(x);
y = find(y);
if (x == y) return;
if (rankv[x] < rankv[y])
par[x] = y;
else {
par[y] = x;
if (rankv[x] == rankv[y])
rankv[x]++;
}
}
bool same(int x, int y) {
return find(x) == find(y);
}
struct edge{
int cost, M, F;
};
edge es[8] = {
edge{ 6831, 4, 3 }, edge{ 4583, 1, 3 }, edge{ 6592, 0, 0 }, edge{ 3063, 0, 1 }, edge{ 4975, 3, 3 }, edge{ 2049, 1, 3 }, edge{ 2104, 4, 2 }, edge{ 781, 2, 2 }
};
bool comp(const edge& e1, const edge& e2){
return e1.cost > e2.cost;
}
int kruskal()
{
sort(es, es + R, comp);
int res = 0;
init (N + M);
for (int i = 0; i < R; i++)
{
edge e = es[i];
if (same(e.F+N, e.M)==0)
{
unite(e.M, e.F + N);
res = res + e.cost;
//cout<<e.cost<<endl;
}
}
return res;
}
int main()
{
cout << 10000 * (N + M)-kruskal() << endl;
return 0;
}