思路:首先路径的选择,如果B点到终点的距离比A点到终点的最短距离短,那么就从A走到B,换句话说,就是每次都是择优选择更靠近终点的点。于是我们可以从终点2跑一次Dijkstra,求出每个点到终点(2号节点)的最短距离,然后就是从起点1开始记忆化搜索,如果满足上面条件的,就记忆化搜索.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1000+10;
const int INF=(1<<30);
int Map[maxn][maxn],dis[maxn],path[maxn],m,n,vis[maxn];
void init()
{
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++)
if(i!=j) Map[i][j]=INF;
else Map[i][j]=0;
}
void Dijkstra(int src)
{
int i,j,minn,pos;
memset(vis,0,sizeof(vis));
for(i = 0; i<=n; i++)
dis[i] = Map[src][i];
dis[src] = 0;
vis[src] = 1;
for(i = 1; i<=n; i++)
{
minn = INF;
pos = 0;
for(j = 1; j<=n; j++)
{
if(minn>dis[j] && !vis[j])
minn = dis[pos = j];
}
vis[pos] = 1;
for(j = 1; j<=n; j++)
if(dis[j]>dis[pos]+Map[pos][j] && !vis[j])
dis[j] = dis[pos]+Map[pos][j];
}
}
int dfs(int u)
{
if(path[u]!=-1) return path[u];
if(u==2) return 1;
path[u]=0;
for(int i=1;i<=n;i++)
if(Map[u][i]!=INF&&dis[u]>dis[i])
path[u]+=dfs(i);
return path[u];
}
int main()
{
while(scanf("%d",&n)&&n)
{
scanf("%d",&m);
int x,y,z;
init();
for(int i = 0; i<m; i++)
{
scanf("%d%d%d",&x,&y,&z);
Map[x][y] = Map[y][x] = z;
}
Dijkstra(2);
memset(path,-1,sizeof(path));
printf("%d\n",dfs(1));
}
}