[UVA][MST] 12507 - Kingdoms
Kingdoms
Kingdoms |
A kingdom has n cities numbered 1 to n, and some bidirectional roads connecting cities. The capital is always city 1.
After a war, all the roads of the kingdom are destroyed. The king wants to rebuild some of the roads to connect the cities, but unfortunately, the kingdom is running out of money. The total cost of rebuilding roads should not exceed K.
Given the list of m roads that can be rebuilt (other roads are severely damaged and cannot be rebuilt), the king decided to maximize the total population in the capital and all other cities that are connected (directly or indirectly) with the capital (we call it ``accessible population"), can you help him?
Input
The first line of input contains a single integer T (T20), the number of test cases. Each test case begins with three integers n ( 4n16), m ( 1m100) and K ( 1K100, 000). The second line contains n positive integers pi ( 1pi10, 000), the population of each city. Each of the following m lines contains three positive integers u, v, c ( 1u, vn, 1c1000), representing a destroyed road connecting city u and v, whose rebuilding cost is c. Note that two cities can be directly connected by more than one road, but a road cannot directly connect a city and itself.
Output
For each test case, print the maximal accessible population.
Sample Input
2 4 6 6 500 400 300 200 1 2 4 1 3 3 1 4 2 4 3 5 2 4 6 3 2 7 4 6 5 500 400 300 200 1 2 4 1 3 3 1 4 2 4 3 5 2 4 6 3 2 7
Sample Output
1100 1000
Problemsetter: Rujia Liu, Special Thanks: Feng Chen, Md. Mahbubul Hasan
看到 n <= 16, 明顯地窮舉 2^n 種連接需求,
然後看這種連接的最小生成樹的成本有沒有低於公費。
#include <stdio.h>
#include <algorithm>
using namespace std;
struct E {
int x, y, v;
};
bool cmp(E a, E b) {
return a.v < b.v;
}
int P[105], R[105];
void init(int n) {
for(int i = 0; i <= n; i++)
P[i] = i, R[i] = 1;
}
int findP(int x) {
return P[x] == x ? x : P[x] = findP(P[x]);
}
int joint(int x, int y) {
x = findP(x);
y = findP(y);
if(x != y) {
if(R[x] > R[y])
R[x] += R[y], P[y] = x;
else
R[y] += R[x], P[x] = y;
return 1;
}
return 0;
}
int main() {
E e[105];
int n, m, K, t, A[105];
int i, j;
scanf("%d", &t);
while(t--) {
scanf("%d %d %d", &n, &m, &K);
for(i = 0; i < n; i++)
scanf("%d", &A[i]);
for(i = 0; i < m; i++) {
scanf("%d %d %d", &e[i].x, &e[i].y, &e[i].v);
e[i].x--;
e[i].y--;
}
sort(e, e+m, cmp);
int res = A[0];
for(i = (1<<n)-1; i >= 0; i -= 2) {
int people = 0, tn = 0;
for(j = 0; j < n; j++)
if((i>>j)&1)
people += A[j], tn++;
if(people <= res)
continue;
int cost = 0, edge = 0;
init(n);
for(j = 0; j < m; j++) {
if(((i>>e[j].x)&1) && ((i>>e[j].y)&1) && joint(e[j].x, e[j].y)) {
edge++;
cost += e[j].v;
}
}
if(edge == tn-1 && cost <= K) {
res = people;
}
}
printf("%d\n", res);
}
return 0;
}