HDU3072 Intelligence System【最小树形图】

题意:从0开始,传消息,问所有人都知道的时候的最小费用。假如两个人在同一连通分量,费用不计


思路:直接求最小树形图会TLE。转化下,求把连通块连起来的最小费用。每个连通块的入边的权取最小值,累加这些值。新图后,是没有环的,所以这样贪心没问题。


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
const int maxn = 5e4+5;
const int maxm = 1e5+5; 

struct edge
{
	int to,next,cost;
}ed[maxm];
int head[maxn], tot;  
int Low[maxn], DFN[maxn], Stack[maxn];  
int Index, top;
bool Instack[maxn]; 
int block,belong[maxn];  
int cost[maxn];
void init(int n)
{
	memset(head, -1, sizeof(head));  
	memset(cost, 0x3f, sizeof(cost));  
    memset(DFN, 0, sizeof(DFN));   
    memset(Instack, false, sizeof(Instack));   
    block = tot = 0;
    Index = top = 0;    
}

void Tarjan(int u,int pre)
{
    int v;
    Low[u] = DFN[u] = ++Index;
    Stack[top++] = u;
    Instack[u] = true;
    for(int i = head[u];i != -1;i = ed[i].next)
    {
        v = ed[i].to;
        //if(v == pre)continue; //无向无重边 用,只要不往回走 
        //if(ed[i].id == pre) continue; //无向图重边判定,不走同一条边 
        if( !DFN[v] )
        {
            Tarjan(v,u);
            //Tarjan(v,ed[i].id); //无向图重边判定
            if( Low[u] > Low[v] )Low[u] = Low[v];
        }
        else if( Instack[v] && Low[u] > DFN[v] )
            Low[u] = DFN[v];
    }
    if(Low[u] == DFN[u])
    {
        block++;
        do
        {
            v = Stack[--top];
            Instack[v] = false;
            belong[v] = block;
        }
        while( v!=u );
    }
}//使无向图双连通,(叶子+1) / 2 

void add(int x,int y,int z)
{
	ed[tot].cost = z;
	ed[tot].to = y;
	ed[tot].next = head[x];
	head[x] = tot++;
}

int main(void)
{
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		init(n);
		for(int i = 0,a,b,c; i < m; i++)
		{
			scanf("%d%d%d",&a,&b,&c);
			add(a,b,c);
		}
		Tarjan(0,-1);
		for(int i = 0; i < n; i++)
		{
			for(int j = head[i]; j != -1; j = ed[j].next)
			{
				int v = ed[j].to;
				if(belong[i] != belong[v])
					cost[belong[v]] = min(cost[belong[v]],ed[j].cost);
			}
		}
		int ans = 0;
		for(int i = 1; i <= block; i++)
		{
			if(i != belong[0])
				ans += cost[i];
		}
		printf("%d\n",ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值