队爷的讲学计划 (强连通缩点+最短路)

来源:互联网 发布:centos wifi 编辑:程序博客网 时间:2024/06/06 00:26

队爷的讲学计划
【问题描述】
队爷为了造福社会,准备到各地去讲学。他的计划中有n个城市,从u到v可能有一条单向道路,通过这条道路所需费用为q。当队爷在u城市讲学完之后,u城市会派出一名使者与他同行,只要使者和他在一起,他到达某个城市就只需要花1的入城费且只需交一次,在路上的费用就可免去。。但是使者要回到u城市,所以使者只会陪他去能找到回u城市的路的城市。。队爷从1号城市开始讲学,若他在u号城市讲学完毕,使者会带他尽可能多的去别的城市。他希望你帮他找出一种方案,使他能讲学到的城市尽可能多,且费用尽可能小。
【输入文件】
第一行2个整数n,m。
接下来m行每行3个整数u,v,q,表示从u到v有一条长度为q
的单向道路。
【输出文件】
一行,两个整数,为最大讲学城市数和最小费用。
【输入样例】
6 6
1 2 3
2 3 7
2 6 4
3 4 5
4 5 4
5 2 3
【输出样例】
6 10
【样例解释】
如上图,从1走到2,2城市使者会带他到3,4,5城市,
回到2城市,再走到6,总费用为3+3+4=10。
【数据规模与约定】
对于20%的数据,1<=n<=20;
对于另外10%的数据,城市网络为一条单向链;
对于60%的数据,1<=m<=200000
对于100%的数据,1<=n<=100000
1<=m<=500000,1<=q<=1000, 保证无自环无重边。

强连通缩点+最短路,注意最短路的时候需要加上该强连通分量内的点数-1。 关于最短路,因为数据比较水,spfa就可以了。

代码如下

program mys;type ab=^node;node=recorddata,ends:longint;next:ab;end;var x,y,z,i,j,k,m,n,t,ans,an:longint;f,dis,g,hh:array[0..500000]of longint;p,pa:array[0..500000]of ab;team:array[0..5000000]of longint;b,zhan:array[0..500000]of boolean;ii:ab;function find(x:longint):longint;begin if f[x]<>x then f[x]:=find(f[x]);exit(f[x]);end;procedure com(x,y,z:longint);var i:ab;begin i:=p[x];new(p[x]);p[x]^.ends:=y;p[x]^.data:=z;p[x]^.next:=i;end;procedure combine(x,y,z:longint);var i:ab;begin i:=pa[x];new(pa[x]);pa[x]^.ends:=y;pa[x]^.data:=z;pa[x]^.next:=i;end;procedure dfs(x:longint);var y:longint;i:ab;begin inc(t);team[x]:=t;b[x]:=true;zhan[x]:=true;i:=p[x];while i<>nil do begin y:=i^.ends;if  not b[y] then dfs(y);y:=find(y);if (zhan[y])and(team[x]>team[y]) then begin team[x]:=team[y];f[x]:=y;end;i:=i^.next;end;zhan[x]:=false;end;procedure spfa;var t,x,h,u,y:longint;i:ab;begin fillchar(b,sizeof(b),false);fillchar(dis,sizeof(dis),$7f);fillchar(team,sizeof(team),0);t:=1; h:=0; team[1]:=1; b[1]:=true; hh[1]:=g[1]; dis[1]:=g[1]-1;while h<t do begin inc(h);u:=team[h];i:=pa[u];b[u]:=false;while i<>nil do beginy:=i^.ends;if (hh[y]<hh[u]+g[y])or((hh[y]=hh[u]+g[y])and(dis[y]>dis[u]+i^.data+g[y]-1)) then begin hh[y]:=hh[u]+g[y];dis[y]:=dis[u]+i^.data+g[y]-1;if b[y]=false then begin inc(t);team[t]:=y;b[y]:=true;end;end;i:=i^.next;end;end;end;begin assign(input,'teach.in');reset(input);assign(output,'teach.out'); rewrite(output);readln(n,m);for i:=1 to m do begin readln(x,y,z);com(x,y,z);end;for i:=1 to n do f[i]:=i;dfs(1);for i:=1 to n do inc(g[find(i)]);for i:=1 to n do begin ii:=p[i];x:=find(i);while ii<>nil do begin if find(ii^.ends)<>x then  combine(x,find(ii^.ends),ii^.data);ii:=ii^.next;end;end;spfa;ans:=maxlongint;an:=0;for i:=1 to n do if (an<hh[i])or((an=hh[i])and(ans>dis[i])) then begin an:=hh[i];ans:=dis[i];end;writeln(an,' ',ans);close(input);close(output);end.
0 0
原创粉丝点击