题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3311
题目大意:n个和尚要去挑水,他们可以再他们所在的地方挑水,也可以再其他m个地方挑水,挑水之前需要挖井,在n+m个地方挖井对应着n+m个费用,然后给定p条边,表示两个地方可以互达,边有边权表示需要的费用。
解题思路: 因为必须覆盖n个和尚,那么便是求一颗包含前n个点的斯坦纳树。
一开始我的做法是将每个点挖井的费用表示在cost[i][st[i]]里,即以i为根并在i挖井的费用,写着写着就蛋疼了写不下去,点的费用会被重复计算好多次,这不是坑爹吗,然后就困了。睡一觉醒来后灵感大爆发,TMD的加个点0,然后连1条边到n+m的点,边权为点权,这样问题就转换成了:求覆盖点0,点1...点n的斯坦纳树,不需考虑点权了,也不会重复计算了。
按上面的思路套个斯坦纳树模版,发现结果全为0.在求解dp[i]的时候,我没有加一些就进行dp[i] = min(dp[i],dp[k]+dp[i-k])。这样结果当然都为0,如dp[7] = dp[4] + dp[2] + dp[1],dp[1] = cost[0][1] = 0,dp[2]=cost[1][2] = 0,dp[4] = cost[2][4] = 0,这样的话一个集合就由若干个单点集合组合,费用都为0.其实这样忽视了一个条件,我们增加的点0是必须和1.2..n绑定在一起的,也就是说必须判断某个集合里是否为点0在。
其实,ans = min(cost[i][(1<<(n+1))-1])(i<=i<=n+m),因为这样的集合包含了所有点,并且这只会是一棵树,也就是答案了。
测试数据:
InPut:
3 1 3
1 2 3 4
1 4 2
2 4 2
3 4 4
4 1 4
5 5 5 5 1
1 5 1
2 5 1
3 5 1
4 5 1
OutPut:
6
5
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
#define MIN (1<<6)
#define MAX 1100
#define INF (1<<29)
#define min(a,b) ((a)<(b)?(a):(b))
struct node {
int v,len;
node *next;
}*head[MAX],tree[MAX*11];
queue<int> qu;
bool in[MAX][MIN];
int n,m,p,nn,ptr,ans,st[MAX];
int well[MAX],cost[MAX][MIN],dp[MAX];
void Initial() {
ptr = 0,nn = (1<<(n+1)) - 1;
memset(st,0,sizeof(st));
memset(in,false,sizeof(in));
memset(head,NULL,sizeof(head));
for (int i = 0; i <= (n+m); ++i)
for (int j = 0; j < MIN; ++j)
cost[i][j] = INF;
for (i = 0; i <= n ; ++i)
st[i] = 1<<i,cost[i][st[i]] = 0;
}
void AddEdge(int a,int b,int c) {
tree[ptr].v = b,tree[ptr].len = c;
tree[ptr].next = head[a],head[a] = &tree[ptr++];
}
void Spfa() {
while (!qu.empty()) {
int i = qu.front() / MAX;
int j = qu.front() % MAX;
qu.pop(),in[i][j] = false;
node *p = head[i];
while (p != NULL) {
int v = p->v,nst = j | st[v];
if (cost[i][j] + p->len < cost[v][nst]) {
cost[v][nst] = cost[i][j] + p->len;
if (nst == j && !in[v][nst])
qu.push(v * MAX + nst),in[v][nst] = true;
}
p = p->next;
}
}
}
void Steiner_Tree() {
int i,j,k;
for (j = 0; j <= nn; ++j){
for (i = 0; i <= (n + m); ++i){
for (k = (j-1)&j; k; k = (k-1) & j)
cost[i][j] = min(cost[i][j],cost[i][k|st[i]]+cost[i][(j-k)|st[i]]);
if (cost[i][j] != INF) qu.push(i * MAX + j),in[i][j] = true;
}
Spfa();
}
}
int Solve_DP() {
int i,j,k;
for (j = 0; j <= nn; ++j) {
dp[j] = INF;
for (i = 0; i <= (n + m); ++i)
dp[j] = min(dp[j],cost[i][j]);
}
//for (i = 1; i <= nn; ++i)
// if (i&1)for (k = (i-1)&i; k; k = (k-1)&i)
// if ((k&1)&&((i-k)&1))dp[i] = min(dp[i],dp[k]+dp[i-k]);
return dp[nn];
}
int main()
{
int i,j,k,a,b,c;
while (scanf("%d%d%d",&n,&m,&p) != EOF) {
for (i = 1; i <= (n + m); ++i)
scanf("%d",&well[i]);
Initial();
for (i = 1; i <= p; ++i) {
scanf("%d%d%d",&a,&b,&c);
AddEdge(a,b,c),AddEdge(b,a,c);
}
for (i = 1; i <= (n + m); ++i)
AddEdge(0,i,well[i]),AddEdge(i,0,well[i]);
Steiner_Tree();
ans = Solve_DP();
printf("%d\n",ans);
}
}
本文ZeroClock原创,但可以转载,因为我们是兄弟。