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
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
--------------------------------------------------------
裸状压dp。
状压dp易写错的地方
1. for循环变量比较多,i, j, k 什么的容易和全局变量搞混,而且 循环变量/循环体 本身也容易写错。
2. 位运算操作符容易和对应的逻辑运算操作符搞混。
----------------------------------------------------------------
此题有坑---重边
----------------------------------------------------------------
#include <bits/stdc++.h>
using namespace std;
int g[18][18], p[18];
const int N(1<<18);
int dp[N], co[N];
int T, n, m, k, u, v, c, ans;
inline int ones(int x){
int res=0;
for(int i=1; i<=n; i++){
if(x&1<<i) res++;
}
return res;
}
inline void trans(int s, int i){
for(int j=1; j<=n; j++){
if(g[i][j]&&!(s&1<<j)&&co[s]+g[i][j]<=k){
int t=s|1<<j;
dp[t]=dp[s]+p[j];
ans=max(ans, dp[t]);
co[t]=co[t]?min(co[t], co[s]+g[i][j]):co[s]+g[i][j];
}
}
}
int main(){
freopen("in", "r", stdin);
for(cin>>T; T--;){
cin>>n>>m>>k;
for(int i=1; i<=n; i++) cin>>p[i];
for(;m--;){
cin>>u>>v>>c;
if(!g[u][v]||g[u][v]>c) g[u][v]=g[v][u]=c;
}
dp[1<<1]=ans=p[1], co[1<<1]=0;
for(int i=1; i<n; i++){ //iterate over ones
for(int j=1<<1, tot=1<<n+1; j<tot; j++){ //iterate over state
if(ones(j)==i&&dp[j]){
for(int k=1; k<=n; k++){ //iterate over bits
if(j&1<<k){
trans(j, k);
}
}
}
}
}
printf("%d\n", ans);
memset(dp, 0, sizeof(dp));
memset(co, 0, sizeof(co));
memset(g, 0, sizeof(g));
}
}