HDU 1142 A Walk Through the Forest
题目链接:传送门
Problem Description
Jimmy experiences a lot of stress at work these days, especially since his accident made working difficult. To relax after a hard day, he likes to walk home. To make things even nicer, his office is on one side of a forest, and his house is on the other. A nice walk through the forest, seeing the birds and chipmunks is quite enjoyable.
The forest is beautiful, and Jimmy wants to take a different route everyday. He also wants to get home before dark, so he always takes a path to make progress towards his house. He considers taking a path from A to B to be progress if there exists a route from B to his home that is shorter than any possible route from A. Calculate how many different routes through the forest Jimmy might take.
Input
Input contains several test cases followed by a line containing 0. Jimmy has numbered each intersection or joining of paths starting with 1. His office is numbered 1, and his house is numbered 2. The first line of each test case gives the number of intersections N, 1 < N ≤ 1000, and the number of paths M. The following M lines each contain a pair of intersections a b and an integer distance 1 ≤ d ≤ 1000000 indicating a path of length d between intersection a and a different intersection b. Jimmy may walk a path any direction he chooses. There is at most one path between any pair of intersections.
Output
For each test case, output a single integer indicating the number of different routes through the forest. You may assume that this number does not exceed 2147483647
Sample Input
5 6
1 3 2
1 4 2
3 4 3
1 5 12
4 2 34
5 2 24
7 8
1 3 1
1 4 1
3 7 1
7 4 1
7 5 1
6 7 1
5 2 1
6 2 1
0
Sample Output
2
4
题目大意:吉米这些天在工作中经历了很多压力,尤其是因为他的意外使工作变得困难。为了在艰难的一天后放松,他喜欢步行回家。为了使事情更美好,他的办公室在森林的一边,他的房子在另一边。在森林里散步,看鸟和花栗鼠很愉快。
森林很美,吉米想每天走一条不同的路线。他还想在天黑之前回家,所以他总是走一条路朝着自己的房子前进。如果有一条从B到他的家的路线比从A到他的家的任何可能的路线都短,他认为从A到B的路线是进步的。计算吉米可能走多少条不同的路线穿过森林。
#include<iostream>
#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
int m[1005][1005],n[1005];
int len[1005];
int s,w,x,y;
void Djistra(int a)
{
int b,c,d,e,f,g;
int vis[1005];
for(b=0;b<=s;b++)
{
len[b]=m[a][b];
vis[b]=0;
}
vis[a]=1;
for(b=1;b<=s;b++)
{
e=INF;
f=0;
for(c=1;c<=s;c++)
{
if(len[c]<e&&!vis[c])
{
e=len[c];
f=c;
}
}
if(f==0)
break;
vis[f]=1;
for(c=1;c<=s;c++)
{
if(!vis[c])
{
if(len[f]+m[f][c]<len[c])
len[c]=len[f]+m[f][c];
}
}
}
}
int dfs(int a)
{
if(n[a]!=0)
return n[a];
if(a==2)
return 1;
int b,c,d;
int sum=0;
for(b=1;b<=s;b++)
{
if(m[a][b]<INF&&len[b]<len[a])
sum+=dfs(b);
n[a]=sum;
}
return sum;
}
int main()
{
int a,b,c,d,e,f;
while(cin>>s)
{
if(s==0)
break;
cin>>w;
for(b=0;b<=s;b++)
{
n[b]=0;
for(c=0;c<=s;c++)
{
if(c==b)
m[c][b]=0;
else
m[b][c]=INF;
}
}
for(c=0;c<w;c++)
{
cin>>d>>e>>f;
m[d][e]=m[e][d]=f;
}
Djistra(2);
cout<<dfs(1)<<endl;
}
}