题意::从起点到终点的所有的最短路中,找出离终点有X个路口的城市一共有几个
开始我用最短路+DFS从起点开始搜,超时了
换了一种方法,从终点开始搜,AC
#include<stdio.h> int N; const int MAX=1e9; int use[1009]; int dis[1009]; int map[1009][1009]; bool hash[1009]; int tempget[1009]; int maxDis; int allPoint; int start,end,shortNum; void dijk() { int i,j,min,rj,from; dis[start]=0; for(i=1;i<=N;i++){ min=MAX; for(j=1;j<=N;j++){ if(use[j]==1)continue; if(min>dis[j]){ min=dis[j]; rj=j; } } from=rj; for(j=1;j<=N;j++){ if(use[j]==1)continue; if(dis[j]>map[from][j]+dis[from]) dis[j]=map[from][j]+dis[from]; } use[rj]=1; } } void dfs(int from,int leftStep,int lenth) //搜的时候从师兄所在的点开始搜 { int i; if(leftStep==0)return ; for(i=1;i<=N;i++){ if(hash[i]==1)continue; if((dis[i]+map[from][i]+lenth)!=dis[end])continue; //这样保证了从终点搜出的点都在最短路上 if(tempget[i]==0){ allPoint++;tempget[i]=1; } hash[i]=1; dfs(i,leftStep-1,lenth+map[from][i]); hash[i]=0; } } int main() { int m,i,j,k; while(scanf("%d%d",&N,&m)!=EOF){ int ll,rr,v; start=N; end=1; allPoint=0; scanf("%d",&maxDis); for(i=1;i<=N;i++){ for(j=1;j<=N;j++){ map[i][j]=MAX; hash[i]=0; } dis[i]=MAX; use[i]=0; tempget[i]=0; } for(i=1;i<=m;i++){ scanf("%d%d%d",&ll,&rr,&v); if(map[ll][rr]>v){ map[ll][rr]=map[rr][ll]=v; } } dijk(); tempget[1]=end; allPoint++; dfs(end,maxDis,0); printf("%d ",allPoint); } return 0; }