poj 3464 http://poj.org/problem?id=3463
问最短路的条数+比最短路权值大 1 的条数
做法 比较一下次短路和最短路的值 若次短路恰好比最短路大1,答案为最短路+次短路条数,否则答案就是最短路条数
1 #include<cstdio> 2 const int inf=0x3f3f3f3f; 3 class Count_short_path { ///最短路与次短路计数Dijkstra_o(MV^2) 4 typedef int typec;///边权的类型 5 static const int ME=1e4+10;///边的个数 6 static const int MV=1e3+10;///点的个数 7 struct E { 8 int v,next; 9 typec w; 10 } e[ME]; 11 int n,le,head[MV],cnt[MV][2],i,j,k,u,v,tmp,flag; 12 typec dist[MV][2],w; 13 bool used[MV][2]; 14 public: 15 void init(int tn) { ///传入点的个数 16 n=tn; 17 le=0; 18 for(i=0; i<=n; i++) head[i]=-1; 19 } 20 void add(int u,int v,typec w) { 21 e[le].v=v; 22 e[le].w=w; 23 e[le].next=head[u]; 24 head[u]=le++; 25 } 26 void solve(int s) { ///传入起点 27 for(i=0; i<=n; i++) { 28 for(j=0; j<2; j++) { 29 cnt[i][j]=0; 30 dist[i][j]=inf; 31 used[i][j]=false; 32 } 33 } 34 dist[s][0]=0; 35 cnt[s][0]=1; 36 for(k=1; k<n*2; k++) { 37 tmp=inf; 38 for(j=0; j<=n; j++) { 39 if(!used[j][0]&&tmp>dist[j][0]) { 40 u=j; 41 flag=0; 42 tmp=dist[j][0]; 43 } else if(!used[j][1]&&tmp>dist[j][1]) { 44 u=j; 45 flag=1; 46 tmp=dist[j][1]; 47 } 48 } 49 if(tmp==inf) break; 50 used[u][flag]=1; 51 for(i=head[u]; ~i; i=e[i].next) { 52 v=e[i].v; 53 w=e[i].w; 54 if(tmp+w<dist[v][0]) { 55 dist[v][1]=dist[v][0]; 56 cnt[v][1]=cnt[v][0]; 57 dist[v][0]=tmp+w; 58 cnt[v][0]=cnt[u][flag]; 59 } 60 else if(tmp+w==dist[v][0]) { 61 cnt[v][0]+=cnt[u][flag]; 62 } 63 else if(tmp+w<dist[v][1]) { 64 dist[v][1]=tmp+w; 65 cnt[v][1]=cnt[u][flag]; 66 } 67 else if(tmp+w==dist[v][1]) { 68 cnt[v][1]+=cnt[u][flag]; 69 } 70 } 71 } 72 } 73 typec getdist(int id,int flag) {///flag==0返回最短路,1返回次短路 74 return dist[id][flag]; 75 } 76 int getcnt(int id,int flag) { ///返回路的个数 77 return cnt[id][flag]; 78 } 79 } g; 80 int main(){ 81 int t,n,m,u,v,w; 82 while(~scanf("%d",&t)){ 83 while(t--){ 84 scanf("%d%d",&n,&m); 85 g.init(n); 86 while(m--){ 87 scanf("%d%d%d",&u,&v,&w); 88 g.add(u,v,w); 89 } 90 scanf("%d%d",&u,&v); 91 g.solve(u); 92 int ans=g.getcnt(v,0); 93 if(g.getdist(v,0)==g.getdist(v,1)-1) ans+=g.getcnt(v,1); 94 printf("%d\n",ans); 95 } 96 } 97 return 0; 98 }