题目:http://acm.hdu.edu.cn/showproblem.php?pid=3072
题意
给一点编号为0,1,2...,n的有向图,求从0点出发的最小树形图。
分析
求出原图的强连通分量并缩点,然后求出除0所在新点以外所有新点的入边权的最小值之和即可。
代码
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
const int N=110000;
using namespace std;
int n,m,x,y,c[N],cnt,sum;
int u[N],v[N],f[N],to[N];
int dfn[N],low[N],is_use[N],Index;
int stack[N],top,is_sta[N];
int nncnt,nm[N],nnum[N];
void tarjan(int nd){
dfn[nd]=low[nd]=++Index;
stack[++top]=nd;
is_use[nd]=is_sta[nd]=1;
int ned=f[nd],nnd=v[ned];
while (ned!=0){
if (is_sta[nnd]) low[nd]=min(low[nd],dfn[nnd]);
else if (!is_use[nnd]){
tarjan(nnd);
low[nd]=min(low[nd],low[nnd]);
}
ned=to[ned]; nnd=v[ned];
}
if (dfn[nd]==low[nd]){
nncnt++;
while (1){
nnum[stack[top]]=nncnt;
is_sta[stack[top]]=0;
top--;
if (stack[top+1]==nd) break;
}
}
}
void init(){
memset(f,0,sizeof f);
memset(to,0,sizeof to);
memset(dfn,0,sizeof dfn);
memset(low,0,sizeof low);
memset(nm,127,sizeof nm);
memset(is_use,0,sizeof is_use);
memset(is_sta,0,sizeof is_sta);
top=cnt=nncnt=Index=sum=0;
}
int main(){
freopen("hdu3072.txt","r",stdin);
while (~scanf("%d%d",&n,&m)){
init();
for (int i=1; i<=m; i++){
scanf("%d%d%d",&x,&y,&c[i]);
u[++cnt]=x+1; v[cnt]=y+1;//为了方便改成从1开始的点
to[cnt]=f[u[cnt]];
f[u[cnt]]=cnt;
}
for (int i=1; i<=n; i++){
if (!dfn[i]) tarjan(i);
}
for (int i=1; i<=n; i++){
int ned=f[i];
while (ned>0){
if (nnum[u[ned]]!=nnum[v[ned]])
nm[nnum[v[ned]]]=min(nm[nnum[v[ned]]],c[ned]);
ned=to[ned];
}
}
for (int i=1; i<=nncnt; i++) if(i!=nnum[1]) sum+=nm[i];
printf("%d\n",sum);
}
return 0;
}