题意:给n个点,现在要使这n个点连通,并且要求代价最小。现在有2个点之间不能直接连通(除了第一个点),求最小代价
思路:先求mst,然后枚举边,对于生成树上的边替换,用树形dp O(N^2)求出每条生成树边的最小替代边。然后替换后的最大值
代码:
#include <cmath> #include <queue> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int inf = 0x3f3f3f3f; inline void RD(int &ret) { char c; int flag = 1 ; do { c = getchar(); if(c == ‘-‘)flag = -1 ; } while(c < ‘0‘ || c > ‘9‘) ; ret = c - ‘0‘; while((c=getchar()) >= ‘0‘ && c <= ‘9‘) ret = ret * 10 + ( c - ‘0‘ ); ret *= flag ; } struct kdq{ int s , e ; double l ; bool operator < (const kdq & fk)const { return l > fk.l ; } } ; #define N 1111 #define M 111111 int st[M] ; int top ; double NMIN[N][N] ; int x[N] , y[N] , cost , n ; double Map[N][N] ; double dis[N] ; bool vis[N] ; vector<int>G[N] ; priority_queue<kdq>qe ; double mst = 0 ; bool ismst[N][N] ; double MINE[N][N] ; double getdis(int i , int j){ return sqrt(1.0 * (x[i] - x[j]) * (x[i] - x[j]) + 1.0 * (y[i] - y[j]) * (y[i] - y[j])) ; } void Prim(){ mst = 0 ; memset(ismst, 0, sizeof ismst); while(!qe.empty())qe.pop() ; for (int i = 0 ; i < n ; i ++ )dis[i] = Map[0][i] , vis[i] = 0 ,G[i].clear() ,qe.push((kdq){0 , i , dis[i]}) ; dis[0] = 0 , vis[0] = 1 ; while(!qe.empty()){ kdq tp = qe.top() ; qe.pop() ; if(vis[tp.e])continue ; mst += Map[tp.s][tp.e] ; vis[tp.e] = 1 ; G[tp.s].push_back(tp.e) ; G[tp.e].push_back(tp.s) ; ismst[tp.e][tp.s] = ismst[tp.s][tp.e] = 1 ; MINE[tp.s][tp.e] = MINE[tp.e][tp.s] = inf ;//删除树边 for (int i = 0 ; i < n ; i ++ )if(!vis[i] && dis[i] > Map[tp.e][i])dis[i] = Map[tp.e][i] , qe.push((kdq){tp.e , i , dis[i]}) ; } } void dfs(int root , int fa , int now){ int sz = G[now].size() ; for (int i = 0 ; i < sz ; i ++ ){ int e = G[now][i] ; if(e != fa)dfs(root , now , e) , MINE[root][now] = min(MINE[root][now] , MINE[root][e]) ; } } void dfs(int fa, int now){ int fk = top ; st[ ++ top] = now ;int sz = G[now].size() ; for (int i = 0 ; i < sz ; i ++ ){ int e = G[now][i] ; if(e != fa)dfs(now , e) ; } if(fa != -1){ NMIN[now][fa] = NMIN[fa][now] = inf ; for (int i = fk + 1 ; i <= top ; i ++ )NMIN[now][fa] = NMIN[fa][now] = min(NMIN[fa][now] , MINE[st[i]][fa]) ; } } void solve(){scanf("%d%d", &n, &cost); for (int i = 0 ; i < n ; i ++ )RD(x[i]) , RD(y[i]) ; for (int i = 0 ; i < n ; i ++ ) for (int j = 0 ; j < n ; j ++ ) MINE[i][j] = Map[i][j] = (i == j) ? 0 : getdis(i , j) ; Prim() ; for (int i = 0 ; i < n ; i ++ )dfs(i , -1 , i ) ; top = 0 ; dfs(-1 , 0) ; double ans = 0 ; for (int i = 0 ; i < n ; i ++ ){ for (int j = 0 ; j < n ; j ++ ){ if(i == 0 || j == 0)continue ; if(!ismst[i][j])continue ; ans = max(ans , NMIN[i][j] - Map[i][j]) ; } } printf("%.2f\n",(ans + mst) * cost) ; } int main() { int _ ; scanf("%d", &_); while(_ --)solve() ; return 0 ; }
【树形DP】 HDU 4756 Install Air Conditioning
原文:http://www.cnblogs.com/Rojo/p/4719670.html