题意: 给定一个无向图n*n(m),求从出发点1到终点2中符合以下条件的路径数目。
<条件:若该路径上的任意段(A,B): 满足B到终点的最短距离比A到终点最短距离要短(即d[A]>d[B]) 则选择B>
思路:Dijkstra+dfs记忆化路径搜索 。
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
using namespace std;
const int SIZE = 1001;
const int INF = 0x3f3f3f3f;
int w[SIZE][SIZE];
int v[SIZE], d[SIZE], dp[SIZE];
int n, m;
void init()
{
memset(w, INF, sizeof(w));
memset(v, 0, sizeof(v));
memset(d, 0, sizeof(d));
memset(dp, 0, sizeof(dp));
}
void Dijkstra(int src)
{
int i, j;
for(i = 1; i <= n; i++) d[i] = (i == src)? 0:INF;
for(i = 1; i <= n; i++)
{
int x, m = INF;
for(int y = 1 ; y <= n; y++) if(!v[y] && m > d[y]) m = d[x=y];
v[x] = 1;
for(int y = 1; y <= n; y++) d[y] <?= d[x] + w[x][y];
}
return ;
}
int dfs(int v, int e) //start, end
{
int i, j;
int sum = 0;
if(dp[v]) return dp[v];
if(v == e) return 1;
for(i = 1; i <= n; i++)
{
if(d[v] > d[i] && w[v][i] != INF)
{
int ans = dfs(i, 2);
sum += ans;
}
}
dp[v] = sum;
return sum;
}
int main()
{
while(scanf("%d%d", &n, &m), n )
{
init();
while(m--)
{
int u, v, cost;
scanf("%d%d%d", &u, &v, &cost);
w[u][v] = w[v][u] = cost;
}
Dijkstra(2);
dfs(1, 2);
printf("%d\n", dp[1]);
}
return 0;
}
#include <stdlib.h>
#include <string.h>
#include <limits.h>
using namespace std;
const int SIZE = 1001;
const int INF = 0x3f3f3f3f;
int w[SIZE][SIZE];
int v[SIZE], d[SIZE], dp[SIZE];
int n, m;
void init()
{
memset(w, INF, sizeof(w));
memset(v, 0, sizeof(v));
memset(d, 0, sizeof(d));
memset(dp, 0, sizeof(dp));
}
void Dijkstra(int src)
{
int i, j;
for(i = 1; i <= n; i++) d[i] = (i == src)? 0:INF;
for(i = 1; i <= n; i++)
{
int x, m = INF;
for(int y = 1 ; y <= n; y++) if(!v[y] && m > d[y]) m = d[x=y];
v[x] = 1;
for(int y = 1; y <= n; y++) d[y] <?= d[x] + w[x][y];
}
return ;
}
int dfs(int v, int e) //start, end
{
int i, j;
int sum = 0;
if(dp[v]) return dp[v];
if(v == e) return 1;
for(i = 1; i <= n; i++)
{
if(d[v] > d[i] && w[v][i] != INF)
{
int ans = dfs(i, 2);
sum += ans;
}
}
dp[v] = sum;
return sum;
}
int main()
{
while(scanf("%d%d", &n, &m), n )
{
init();
while(m--)
{
int u, v, cost;
scanf("%d%d%d", &u, &v, &cost);
w[u][v] = w[v][u] = cost;
}
Dijkstra(2);
dfs(1, 2);
printf("%d\n", dp[1]);
}
return 0;
}