zoukankan      html  css  js  c++  java
  • 牛客练习赛76 D 魔物消灭计划 (斯坦纳树)

    题目链接:https://ac.nowcoder.com/acm/contest/10845/D

    斯坦纳树:联通若干特殊点的最小生成树

    该题中因为同种宝石间传送无需花费代价,所以把同种宝石的城市缩成一个特殊点,然后求斯坦纳树即可

    斯坦纳树求解:
    (dp[i][S]) 表示以 (i) 为根,联通特殊点的状态为 (S) 花费的最小代价
    转移分为两部分

    1. (dp[i][S] = min(dp[i][S], dp[i][sub] + dp[i][S ^ sub])
      其中枚举子集使用以下技巧 (复杂度为 $O(3^n)):
    for(int sub = S & (S - 1) ; sub ; sub = S & (sub - 1))
    
    1. (dp[i][S] = min(dp[i][S], dp[j][S] + w[i][j]))
      第二部分转移就是三角形不等式,dijstra即可
    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    typedef pair<int, int> P;
    
    #define mk make_pair
    
    const int maxn = 610;
    
    int n, m, k, x, y; 
    int a[maxn], id[maxn];
    int dp[maxn][(1 << 10) + 10];
    
    int h[maxn], cnt;
    struct E{
    	int to, next, cost;
    }e[maxn << 1];
    void add(int u, int v, int w){
    	e[++cnt].to = v;
    	e[cnt].cost = w;
    	e[cnt].next = h[u];
    	h[u] = cnt;
    }
    
    priority_queue<P, vector<P>, greater<P> > q;
    int vis[maxn];
    
    void dij(int S){
    	memset(vis, 0, sizeof(vis));
    	while(!q.empty()){
    		P p = q.top(); q.pop();
    		int u = p.second;
    		
    		if(vis[u]) continue;
    		vis[u] = 1;
    		
    		for(int i = h[u] ; i != -1 ; i = e[i].next){
    			int w = e[i].cost, v = e[i].to;
    			if(dp[v][S] > dp[u][S] + w){
    				dp[v][S] = dp[u][S] + w;
    				q.push(mk(dp[v][S], v));
    			}
    		}
    	}
    }
    
    ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }
    
    int main(){
    	memset(h, -1, sizeof(h));
    	
    	n = read(), m = read(), k = read(), x = read(), y = read();
    	id[x] = k + 1, id[y] = k + 2; k += 2;
    	
    	int tot = k;
    	for(int i = 1 ; i <= n ; ++i){
    		a[i] = read();
    		if(i == x || i == y) continue;
    		if(a[i]) id[i] = a[i];
    		else id[i] = ++tot;
    	}
    	
    	n = tot;
    	
    	int u, v, w;
    	for(int i = 1 ; i <= m ; ++i){
    		u = read(), v = read(), w = read();
    		add(id[u], id[v], w), add(id[v], id[u], w);
    	}
    	
    	memset(dp, 0x3f, sizeof(dp));
    	
    	for(int i = 1 ; i <= k ; ++i) dp[i][1 << (i - 1)] = 0;
    	
    	for(int S = 1 ; S < (1 << k) ; ++S){
    		for(int i = 1 ; i <= n ; ++i){
    			for(int sub = S & (S - 1) ; sub ; sub = S & (sub - 1)){
    				dp[i][S] = min(dp[i][S], dp[i][sub] + dp[i][S ^ sub]);
    			}
    			if(dp[i][S] != 0x3f3f3f3f) q.push(mk(dp[i][S], i));
    		}
    		dij(S);
    	}
    	
    	printf("%d
    ", dp[1][(1 << k) - 1]);
    	
    	return 0;
    }     
    
  • 相关阅读:
    HDU-5980
    HDU-5974
    HDU-5979
    关于position的定位
    javascript学习笔记w3chool
    表单相关css技巧
    fis压缩工具的使用
    将HTML页面内容存入json数组
    中介PHP连接前台HTML与数据库MySQL
    lesscss的使用
  • 原文地址:https://www.cnblogs.com/tuchen/p/14320421.html
Copyright © 2011-2022 走看看