C - 掌握魔法の东东 I
题目描述
东东在老家农村无聊,想种田。农田有 n 块,编号从 1~n。种田要灌氵
众所周知东东是一个魔法师,他可以消耗一定的 MP 在一块田上施展魔法,使得黄河之水天上来。他也可以消耗一定的 MP 在两块田的渠上建立传送门,使得这块田引用那块有水的田的水。 (1<=n<=3e2)
黄河之水天上来的消耗是 Wi,i 是农田编号 (1<=Wi<=1e5)
建立传送门的消耗是 Pij,i、j 是农田编号 (1<= Pij <=1e5, Pij = Pji, Pii =0)
东东为所有的田灌氵的最小消耗
Input
第1行:一个数n
第2行到第n+1行:数wi
第n+2行到第2n+1行:矩阵即pij矩阵
Output
东东最小消耗的MP值
Example
Input
4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0
Output
9
解题思路
该题意为求最小生成树,可将题中“天上之水”看作一个超点,该点与其他所有点都有一条边。使用Kruscal算法求最小生成树即可。复杂度为O(n)。
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#define maxn 100100
using namespace std;
struct edge {
int u,v,w;
bool operator< (const edge &p) {
return w<p.w;
}
}Edges[maxn];
int tot=0;
void addEdge(int u,int v,int w) {
tot++;
Edges[tot].u=u;
Edges[tot].v=v;
Edges[tot].w=w;
}
int par[maxn];
int N,ans=0;
int find(int x) {
return par[x]=(x==par[x]? x:find(par[x]));
}
void kruscal() {
int cnt=0;
for(int i=1;i<=tot;i++) {
int set1=find(Edges[i].u),
set2=find(Edges[i].v);
if(set1==set2) continue;
else {
ans+=Edges[i].w;
par[find(Edges[i].v)]=find(Edges[i].u);
cnt++;
}
if(cnt==N) break;
}
}
int main() {
scanf("%d",&N);
for(int i=0;i<=N;i++) par[i]=i;
for(int i=1;i<=N;i++) {
int w_;
scanf("%d",&w_);
addEdge(0,i,w_);
}
for(int i=1;i<=N;i++)
for(int j=1;j<=N;j++) {
int w_; scanf("%d",&w_);
if(i!=j) addEdge(i,j,w_);
}
sort(Edges+1,Edges+tot+1);
kruscal();
printf("%d\n",ans);
return 0;
}