[洛谷1550] 打井

题意:

给出n个点,n^2条边,每个点有一个权值,每条边也有一个权值,你需要选择一些点打井,并选择一些边使井水流通到别的结点,求所有点都有水流通的最小代价。

题解:

最小生成树;

题目就是要你以最小的代价构出一个森林,但是对于点权不好处理,我们考虑将点权转化为边权,从而将问题转化为全图的最小生成树;

若何将森林转化为一棵树,考虑建一个虚拟结点向所有点连边,边权为点的点权,在新图上做最小生成树即可。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 310
#define ll long long
using namespace std;

int g[N][N],fa[N],w[N];

struct Edge {
  int x,y,z;
  bool operator < (const Edge &a) const {
    return z<a.z;
  }
}e[90100];

int gi() {
  int x=0,o=1; char ch=getchar();
  while(ch!='-' && (ch<'0' || ch>'9')) ch=getchar();
  if(ch=='-') o=-1,ch=getchar();
  while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
  return o*x;
}

int find(int x) {
  return x==fa[x]?x:fa[x]=find(fa[x]);
}

int main() {
  int n,cnt,k,ans;
  n=gi(),cnt=k=ans=0;
  for(int i=1; i<=n; i++) {
    w[i]=gi();
    e[++cnt].x=0,e[cnt].y=i,e[cnt].z=w[i];
  }
  for(int i=1; i<=n; i++)
    for(int j=1; j<=n; j++) {
      g[i][j]=gi();      
      if(!g[j][i] && i!=j) e[++cnt].x=i,e[cnt].y=j,e[cnt].z=g[i][j];
    }
  sort(e+1,e+cnt+1);
  for(int i=0; i<=n; i++) fa[i]=i;
  for(int i=1; i<=cnt; i++) {
    int x=find(e[i].x),y=find(e[i].y);
    if(x==y) continue;
    fa[y]=x,k++,ans+=e[i].z;
    if(k==n) break;
  }
  printf("%d", ans);
  return 0;
}
posted @ 2017-10-23 19:10  HLX_Y  阅读(125)  评论(0编辑  收藏  举报