题意:从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;
}