掌握魔法の东东 I(最小生成树kruskal)

问题描述

东东在老家农村无聊,想种田。农田有 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值

Sample input

4
5
4
4
3
0 2 2 2
2 0 3 3
2 3 0 4
2 3 4 0

Sample output

9

解题思路

这个题如果不考虑黄河之水天上来这种情况,就是一个裸的最小生成树,加入了一个灌水操作,将难度提升(果然不要随便灌水)。

我们可以这样思考,增加一个天结点0号,灌水消耗的MP就成了0到这些点的路径(或者理解为消耗MP在天上到地上的结点建立传送门,地上的结点就可以引用天上的水)。然后我们直接对着这个n+1个点到图来跑最小生成树就行了!

完整代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

const int maxn=300+10;
struct node
{
    int x,y,w;
};
node a[maxn*maxn+maxn+10];
int par[maxn],rnk[maxn],ans;
void init(int n)
{
    for (int i=0; i<=n; i++)
    {
        par[i]=i;
        rnk[i]=1;
    }
}
int find(int x)
{
    return par[x]==x ? x : par[x]=find(par[x]);
}
bool unite(int x,int y)
{
    x=find(x); y=find(y);
    if(x==y) return false;

    if(rnk[x]>rnk[y]) swap(x,y);
    par[x]=y; rnk[y]+=rnk[x]; rnk[x]=rnk[y];
    return true;
}
int getint()
{
    int x=0,s=1;
    char ch=' ';
    while(ch<'0' || ch>'9')
    {
        ch=getchar();
        if(ch=='-') s=-1;
    }
    while(ch>='0' && ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*s;
}
bool comp(node a,node b)
{
    return a.w<b.w;
}
int main()
{
    int n=getint();
    for (int i=1; i<=n; i++)//天结点加入
    {
        int x=getint();
        a[i].x=0; a[i].y=i; a[i].w=x;
    }
    int cnt=n;
    for (int i=1; i<=n; i++)
    {
        for (int j=1; j<=n; j++)
        {
            int x=getint();
            if(i==j) continue;
            a[++cnt].x=i; a[cnt].y=j; a[cnt].w=x;
        }
    }
    sort(a+1,a+1+cnt,comp);
    
    int tot=0;
    init(n);
    for (int i=1; i<=cnt; i++)
    {
        if(unite(a[i].x,a[i].y))
        {
            tot++; ans+=a[i].w;
        }
        if(tot==n)
            break;
    }
    printf("%d\n",ans);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值