http://acm.hdu.edu.cn/showproblem.php?pid=1142
题意:n个点m个关系,起点是1,终点是2(家)。这里主人公每当选择路A到B时有一个要求:“if there exists a route from B to his home that is shorter than any possible route from A”,翻译为家到B的最短路小于家到A的最短路,其实就是我们直观的想法,每走一步就要离家近一点。问满足这样条件路径的条数有多少。
思路:首先每次选择路的时候比较的是到2的最短路,那么我们就求从2到所有节点的单源最短路。然后我们找满足这样条件的路,注意这条件在松弛过后的图中使用,其实就是贪心算法,求出的必定是最短路。接着用记忆化搜索保存路径条数,起点的cnt值就是最多的条数。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
using namespace std;
typedef long long LL;
const int N = 1005;
const int INF = 0x3f3f3f3f;
int dis[N], G[N][N], cnt[N], n;//cnt保存满足条件路径的条数
bool vis[N];
void spfa(int s)
{
memset(vis, 0, sizeof(vis));
queue<int>que;
for(int i = 1; i <= n; i++)
dis[i] = INF;
dis[s] = 0;
vis[s] = true;
que.push(s);
while(!que.empty())
{
int now = que.front();
que.pop();
vis[now] = false;
for(int i = 1; i <= n; i++)
{
if(dis[now]+G[now][i]<dis[i])
{
dis[i] = dis[now]+G[now][i];
if(!vis[i])
{
vis[i] = true;
que.push(i);
}
}
}
}
}
int dfs(int s)
{
if(s == 2) return cnt[2] = 1;
if(cnt[s] >= 0) return cnt[s];
else
{
int sum = 0;
for(int i = 1; i <= n; i++)
{
if(G[s][i] != INF && dis[i]<dis[s])
sum+=dfs(i);
}
return cnt[s] = sum;
}
}
int main()
{
// freopen("in.txt", "r", stdin);
int m, s, e, w;
while(~scanf("%d", &n))
{
if(n == 0) break;
scanf("%d", &m);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
if(i == j) G[i][j] = 0;
else G[i][j] = INF;
}
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &s, &e, &w);
G[s][e] = G[e][s] = w;
}
spfa(2);
memset(cnt, -1, sizeof(cnt));
printf("%d\n", dfs(1));
}
return 0;
}