URAL-1982 Electrification Plan 最小生成树

  题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1982

  题意:无向图,给n个点,n^2条边,每条边有个一权值,其中有k个点有发电站,给出这k个点的编号,选择最小权值的边,求使得剩下的点都能接收到电。

  发电站之间显然不能有边,那么把k个点合成一个点,然后在图上就MST就可以了。

 //STATUS:C++_AC_31MS_401KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef __int64 LL;
typedef unsigned __int64 ULL;
//const
const int N=;
const int INF=0x3f3f3f3f;
const int MOD=,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e15;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End struct Edge{
int u,v,val;
bool operator < (const Edge& a)const {
return val<a.val;
}
}e[N*N];
int n,k;
int id[N],p[N],w[N][N]; int find(int x){return p[x]==x?x:p[x]=find(p[x]);} int main()
{
// freopen("in.txt","r",stdin);
int i,j,a,x,y,ans,cnt;
while(~scanf("%d%d",&n,&k))
{
mem(id,);
for(i=;i<k;i++){
scanf("%d",&a);
id[a]=;
}
k=;
for(i=;i<=n;i++){
if(id[i])continue;
id[i]=k++;
}
mem(w,INF);
for(i=;i<=n;i++){
for(j=;j<=n;j++){
scanf("%d",&a);
w[id[i]][id[j]]=Min(w[id[i]][id[j]],a);
}
}
cnt=;
for(i=;i<k;i++){
for(j=i+;j<k;j++){
e[cnt].u=i,e[cnt].v=j;
e[cnt].val=w[i][j];
cnt++;
}
}
sort(e,e+cnt);
ans=;
for(i=;i<k;i++)p[i]=i;
for(i=;i<cnt;i++){
x=find(e[i].u);y=find(e[i].v);
if(x!=y){
p[y]=x;
ans+=e[i].val;
}
} printf("%d\n",ans);
}
return ;
}
上一篇:json库的编译方法和vs2010中导入第三方库的方法


下一篇:面试题:m个长度为n的ordered array,求top k 个 数字