CSU 1116 Kingdoms

来源:互联网 发布:java多线程输出1到100 编辑:程序博客网 时间:2024/06/06 01:24

Description

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 (T<=20), the number of test cases. 
Each test case begins with three integers n(4<=n<=16), m(1<=m<=100) and K(1<=K<=100,000). 
The second line contains n positive integers pi (1<=pi<=10,000), the population of each city. 
Each of the following m lines contains three positive integers u, v, c (1<=u,v<=n, 1<=c<=1000), 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

24 6 6500 400 300 2001 2 41 3 31 4 24 3 52 4 63 2 74 6 5500 400 300 2001 2 41 3 31 4 24 3 52 4 63 2 7 

Sample Output

1100

1000

状态压缩枚举所有状态,然后用最小生成数计算连通该状态的最小权值,判断是否小于k,记录最大值即可。

#include<stdio.h>#include<algorithm>#include<iostream>#include<cstring>using namespace std;const int maxn=105;struct abc{int x,y,z;abc(){}abc(int x,int y,int z):x(x),y(y),z(z){}}b[maxn];bool cmp(const abc&a,const abc&b){return a.z<b.z;}int T,n,m,K,fa[maxn],a[maxn],ans;int get(int x){if (fa[x]!=x) fa[x]=get(fa[x]);return fa[x];}int main(){scanf("%d",&T);while (T--){scanf("%d%d%d",&n,&m,&K);for (int i=0;i<n;i++) scanf("%d",&a[i]);for (int i=0;i<m;i++) {scanf("%d%d%d",&b[i].x,&b[i].y,&b[i].z);}sort(b,b+m,cmp);int N=(1<<n)-1;ans=0;for (int i=0;i<=N;i++)if (i&1){for (int j=1;j<=n;j++) fa[j]=j;int tot=0;for (int j=0;j<m;j++)if (i&(1<<((b[j].x)-1)))if (i&(1<<((b[j].y)-1))){int x=get(b[j].x);int y=get(b[j].y);if (x!=y) {fa[x]=y;tot+=b[j].z;}}for (int j=0;j<n;j++)if (i&(1<<j))if (get(j+1)!=get(1)) tot=K+1;if (tot<=K){int sum=0;for (int j=0;j<n;j++)if (i&(1<<j)) sum+=a[j];ans=max(ans,sum);}}printf("%d\n",ans);}}



0 0
原创粉丝点击