题目大意
有一个信息要通知给所有人,同一个强连通分量内的人互相传递没有消耗,对于每一对给出的a b c表示a 传递给 b 消耗为 c,问把消息传递给所有人的最小消耗(有重边)
思路
求图中的强连通分量,缩点,重新建图,每一个强连通分量内的点我们只传递一个就行了,定义一个cost数组,cost[i]表示传递给编号为 i 的强连通分量的消耗最小值,首先将cost[i]初始化为从0到 i 内的所有边上的消耗最小值,然后在重新建图的过程中,如果有边能从第 i 个强连通分量传递到第 j 个,如果消耗更小,将cost[j]更新为更小的值,最后输出所有点的cost值的和即可
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstring>
#define mem(a) memset(a, 0, sizeof (a))
using namespace std;
struct p{
int pos, dist;
p(){}
p(int pos, int dist){this->pos = pos;this->dist = dist;}
};
const int N = 50010, M = 100010;
int head[N], nex[M], st[N], dfn[N], low[N], v[N], num, top, k, cnt, n, m, cost[N], c[N];
p node[M], node1[M];
int vis[N], head1[N], nex1[M];
void pre_work(){
mem(st), mem(dfn), mem(low), mem(v), mem(node), mem(c), mem(vis);
mem(head1), mem(nex1), mem(node1);
memset(head, -1, sizeof head);
memset(nex, -1, sizeof nex);
memset(cost, 0x3f, sizeof cost);
top = k = num = cnt = 0;
}
void add(int a, int b, int c){
node[++k].pos = b;node[k].dist = c;nex[k] = head[a];head[a] = k;
}
void add1(int a, int b, int c){
node1[++k].pos = b;node1[k].dist = c;nex1[k] = head1[a];head1[a] = k;
}
void init(){
for (int i = 0; i < m; i++){int a, b, c;scanf("%d %d %d", &a, &b, &c);add(a, b, c);}
}
void tarjan(int x){
st[++top] = x;
v[x] = 1;
dfn[x] = low[x] = ++num;
for (int i = head[x]; i != -1; i = nex[i]){
int y = node[i].pos;
if(dfn[y] == 0){
tarjan(y);
low[x] = min(low[x], low[y]);
}
else if(v[y]){
low[x] = min(low[x], dfn[y]);
}
}
if(dfn[x] == low[x]){
++cnt;
while (1){
int t = st[top--];
v[t] = 0;
c[t] = cnt;
if(t == x)break;
}
}
}
void solve(){
pre_work();
init();
for (int i = 0; i < n; i++)if(!dfn[i])tarjan(i);
// for (int i = 0; i < n; i++)printf("%d : %d\n", i, c[i]);
// system("pause");
cost[c[0]] = 0;
k = 0;
for (int i = 0; i < n; i++){
for (int j = head[i]; j != -1; j = nex[j]){
if(c[i] != c[node[j].pos]){
add1(c[i], c[node[j].pos], node[j].dist);
}
if(i == 0){
cost[c[node[j].pos]] = min(cost[c[node[j].pos]], node[j].dist);
}
}
}
for (int i = 1; i <= cnt; i++){
for (int j = head1[i]; j; j = nex1[j]){
cost[node1[j].pos] = min(cost[node1[j].pos], node1[j].dist);
}
}
int res = 0;
for (int i = 1; i <= cnt; i++){
// printf("%d : %d\n", i, cost[i]);
res += cost[i];
}
printf("%d\n", res);
}
int main()
{
while (~scanf("%d %d", &n, &m) && (n + m)){
solve();
}
return 0;
}