HDU--1142--A Walk Through the Forest--深廣搜/DP/最短路徑/記憶化搜索
A Walk Through the Forest
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5948 Accepted Submission(s): 2191
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
題意:和HDU1978一樣的題目,只不過那裡的是給的地圖,這裡是給的稀疏矩陣,給你M組輸入信息a,b,c表示a到b距離為c,求從1到2的路線數,要求:A能走向B的前提是B到2的最短路比A短
解析:也沒什麼好說的,從2做出到達每點的最短距離,然後從1開始按照這個距離遞減去搜索
#include
#include
#include
#define Max 2147483648
using namespace std;
int n,dd[4][2]={0,1,0,-1,1,0,-1,0};
__int64 m,dp[1111],dis[1111],mm[1111][1111];//要用64位,不然2147483648會出錯的
int vis[1111];
void dj()//djkstra算法,迪傑斯特拉
{
int i,j,k,l;
__int64 Min;
memset(vis,0,sizeof(vis));
for(i=1;i<=n;i++)
dis[i]=mm[2][i];
dis[2]=0;
for(i=1;i<=n;i++)
{
Min=Max;
for(j=1;j<=n;j++) //從沒有訪問過的點中找距離2最近的
if(vis[j]==0&&Min>dis[j])
{
Min=dis[j]; //記錄最小值
l=j; //記錄下標
}
if(Min==Max)break; //如果沒有找到就結束
vis[l]=1; //標記這一點已經訪問
for(j=1;j<=n;j++) //用這個最近的點去更新其他點,這一步的術語叫做松弛
{
if(dis[j]>dis[l]+mm[l][j]) //松弛
{
dis[j]=dis[l]+mm[l][j];
}
}
}
}
__int64 dfs(int x)//按照先前求出的最短路徑值遞減去搜索
{
int i,j,k,l;
if(dp[x])return dp[x]; //記憶化搜索的操作,避免重復搜
for(i=1;i<=n;i++)
if(mm[x][i]c) //因為沒看題,所以不確定有沒有重邊,反正這樣寫了不會錯咯
mm[a][b]=mm[b][a]=c;
}
dj();
memset(vis,0,sizeof(vis));
memset(dp,0,sizeof(dp));
dp[2]=1;
dfs(1);
printf("%I64d\n",dp[1]);
}
return 0;
}
總結:越寫越順了,對寫記憶化搜索也越來越有手感了,感覺跟妹子拉手一樣,根本停不下來啊