最小树形图

日常%一发mmh学长。
时间复杂度为O(n * m)。
据说tarjan大神有一个(m+nlogn)的算法,但是找不到资料。。。
①P4716 【模板】最小树形图:
题目背景
这是一道模板题。

题目描述
给定包含 n 个结点, m 条有向边的一个图。试求一棵以结点 r 为根的最小树形图,并输出最小树形图每条边的权值之和,如果没有以 r 为根的最小树形图,输出 −1。

输入格式
第一行包含三个整数 n,m,r,意义同题目所述。

接下来 m 行,每行包含三个整数 u,v,w,表示图中存在一条从 u 指向 v 的权值为 w 的有向边。

输出格式
如果原图中存在以 r 为根的最小树形图,就输出最小树形图每条边的权值之和,否则输出 −1。

输入输出样例
输入 #1 复制
4 6 1
1 2 3
1 3 1
4 1 2
4 2 2
3 2 1
3 4 1
输出 #1 复制
3
输入 #2 复制
4 6 3
1 2 3
1 3 1
4 1 2
4 2 2
3 2 1
3 4 1
输出 #2 复制
4
输入 #3 复制
4 6 2
1 2 3
1 3 1
4 1 2
4 2 2
3 2 1
3 4 1
输出 #3 复制
-1
说明/提示
样例 1 解释

最小树形图中包含第 2, 5, 6 三条边,总权值为 1 + 1 + 1 = 3
样例 2 解释

最小树形图中包含第 3, 5, 6 三条边,总权值为 2 + 1 + 1 = 4
样例 3 解释

无法构成最小树形图,故输出 −1 。

数据范围

对于所有数据,1≤u,v≤n≤100, 1≤m≤1e4

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<vector>
#define ll long long
#define llu unsigned ll
using namespace std;
const int maxn=110;
const int inf=0x3f3f3f3f;
int n,m,root;
int in[maxn],id[maxn],pre[maxn],ha[maxn];
struct node
{
   
    int x,y,z;
}a[maxn*maxn];

int zl(void)
{
   
    int ans=0;
    while(1)
    {
   
        int cnt=0;
        //初始化
        for(int i=1;i<=n;i++)
            in[i]=inf,ha[i]=0,id[i]=0;

        //求最小入边
        for(int i=1;i<=m;i++)
        {
   
            if(a[i].x==a[i].y) continue;
            if(in[a[i].y]>a[i].z)
            {
   
                in[a[i].y]=a[i].z;
                pre[a[i].y]=a[i].x;
            }
        }

        //有除了根节点以外的孤立点
        //则不存在
        for(int i=1;i<=n;i++)
            if(i!=root&&in[i]==inf) return -1;


        for(int i=1;i<=n;i++)
        {
   
            if(i==root) continue;
            ans+=in[i];
            int t=i;
            while(ha[t]!=i&&!id[t]&&t!=root)
                ha[t]=i,t=pre[t];
            if(!id[t]&&t!=root)
            {
   
                id[t]=++cnt;
                for(int j=pre[t];j!=t;j=pre[j])
                    id[j]=cnt;
            }
        }

        //无环则成功找到最小生成树
        if(!cnt) break;
        for(int i=1;i<=n;i++)
            if(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值