1. 程式人生 > >HDUOJ 1428

HDUOJ 1428

漫步校園

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5161    Accepted Submission(s): 1610


Problem Description LL最近沉迷於AC不能自拔,每天寢室、機房兩點一線。由於長時間坐在電腦邊,缺乏運動。他決定充分利用每次從寢室到機房的時間,在校園裡散散步。整個HDU校園呈方形佈局,可劃分為n*n個小方格,代表各個區域。例如LL居住的18號宿舍位於校園的西北角,即方格(1,1)代表的地方,而機房所在的第三實驗樓處於東南端的(n,n)。因有多條路線可以選擇,LL希望每次的散步路線都不一樣。另外,他考慮從A區域到B區域僅當存在一條從B到機房的路線比任何一條從A到機房的路線更近(否則可能永遠都到不了機房了…)。現在他想知道的是,所有滿足要求的路線一共有多少條。你能告訴他嗎?  

 

Input 每組測試資料的第一行為n(2=<n<=50),接下來的n行每行有n個數,代表經過每個區域所花的時間t(0<t<=50)(由於寢室與機房均在三樓,故起點與終點也得費時)。  

 

Output 針對每組測試資料,輸出總的路線數(小於2^63)。  

 

Sample Input 3 1 2 3 1 2 3 1 2 3 3 1 1 1 1 1 1 1 1 1  

 

Sample Output 1 6   BFS
  相對於普通的BFS題,難點在於記錄最短路的條數,在適當的時候num++,HDU討論版上大佬們的思路是從終點開始搜尋。   用記憶化搜尋也可以做。   新學到的奇巧淫技是對比較運算子進行過載,可以省去一部分麻煩。   以下是AC程式碼:  
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4
#include <algorithm> 5 #include <cmath> 6 #include <queue> 7 8 using namespace std; 9 10 const int INF = 0x3f3f3f3f;//無窮大 11 const int maxn = 51; 12 13 int go[4][2] = { 1,0,-1,0,0,1,0,-1 };//方向 14 struct node 15 { 16 int x, y; 17 }; 18 19 int board[maxn][maxn];//記錄位置(i,j)的值 20 int dis[maxn][maxn];//位置(i,j)所經歷的最短路 21 int vis[maxn][maxn], n;//記錄是否走過 22 23 bool operator < (const node &t1, const node &t2) 24 { 25 return dis[t1.x][t1.y] > dis[t2.x][t2.y]; 26 }//過載了比較運算子,用於 27 28 long long num[maxn][maxn];//注意資料範圍 29 30 void bfs() 31 { 32 int i; 33 priority_queue<node> q;//定義一個優先佇列 34 node now, next;//動態儲存現在所在位置和下一步的位置對應的值 35 36 now.x = n; 37 now.y = n;//重點,從重點開始搜尋 38 39 q.push(now); 40 memset(vis, 0, sizeof(vis));//根據求最小的決策,初始化為0 41 vis[n][n] = 1;//搜尋開始 42 while (!q.empty())//搜尋持續到佇列為空 43 { 44 now = q.top(); 45 q.pop(); 46 for (i = 0; i <= 3; i++) 47 { 48 next.x = now.x + go[i][0]; 49 next.y = now.y + go[i][1]; 50 if (next.x >= 1 && next.x <= n && next.y >= 1 && next.y <= n && dis[next.x][next.y] > dis[now.x][now.y]) 51 //加上計數陣列累加的條件 52 { 53 num[next.x][next.y] += num[now.x][now.y];//記錄最短路的數量 54 if (!vis[next.x][next.y] && dis[next.x][next.y] >= dis[now.x][now.y] + board[next.x][next.y]) 55 { 56 dis[next.x][next.y] = dis[now.x][now.y] + board[next.x][next.y]; 57 vis[next.x][next.y] = 1;//將next標記為已訪問 58 q.push(next);//更新佇列 59 } 60 } 61 } 62 } 63 } 64 65 int main() 66 { 67 int i, j; 68 while (~scanf_s("%d", &n)) 69 { 70 memset(dis, 0x3f3f, sizeof(dis)); 71 memset(num, 0, sizeof(num)); 72 num[n][n] = 1; 73 74 for (i = 1; i <= n; i++) 75 for (j = 1; j <= n; j++) 76 scanf_s("%d", &board[i][j]); 77 78 dis[n][n] = board[n][n]; 79 80 bfs(); 81 82 printf("%I64d\n", num[1][1]);//long long 型別對應的格式字元 83 } 84 return 0; 85 }