题意:从某一点出发,经历所有的点,使费用最小,每条边是有费用的。
缩点,建立DAG
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define fread(zcc) freopen(zcc,"r",stdin)
#define fwrite(zcc) freopen(zcc,"w",stdout)
using namespace std;
const int maxn=50005;
const int inf=999999;
struct edge{
int to,cost;
edge(){}
edge(int a,int b):to(a),cost(b){}
};
vector<edge> G[maxn];
int low[maxn],dfn[maxn],belong[maxn],s[maxn];
int num,cnt,top;
bool ins[maxn];
void dfs(int u){
low[u]=dfn[u]=++num;
s[top++]=u;
ins[u]=true;
int N=G[u].size();
for(int i=0;i<N;i++){
int v=G[u][i].to;
if(!dfn[v]){
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(ins[v]&&low[u]>dfn[v]){
low[u]=dfn[v];
}
}
if(low[u]==dfn[u]){
int v=-1;
cnt++;
while(v!=u){
v=s[--top];
ins[v]=false;
belong[v]=cnt;
}
}
}
void Tarjan(int n){
num=top=cnt=0;
cl(ins,false);
cl(belong,0);
cl(dfn,0);
for(int i=1;i<=n;i++){
if(!dfn[i])dfs(i);
}
}
int in[maxn];
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<=n;i++){
G[i].clear();
}
for(int i=0;i<m;i++){
int x,y,st;
scanf("%d%d%d",&x,&y,&st);
x++;y++;
G[x].pb(edge(y,st));
}
Tarjan(n);
for(int i=0;i<=cnt;i++)in[i]=inf;
for(int i=1;i<=n;i++){
for(int j=0;j<G[i].size();j++){
int v=G[i][j].to;
if(belong[i]!=belong[v]){
in[belong[v]]=min(in[belong[v]],G[i][j].cost);//建立DAG图,然后in数字保存到该点的最小边权
}
}
}
int sum=0;
for(int i=1;i<=cnt;i++){
if(in[i]==inf)continue;//因为有入度是0的点,是第一个通知的人,没有边权
sum+=in[i];
}
printf("%d\n",sum);
}
return 0;
}