漫步校园
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1572 Accepted Submission(s): 447
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
Author
LL
Source
Recommend
linle
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct point {
int x;
int y;
};
int direction[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int distances[51][51];//distances[i][j]表示该点到终点的最小距离
int map[51][51];//map[i][j]表示经过该点的时间
__int64 sum[51][51];//sum[i][j]表示该点到终点的路线总数
int n;
//bfs找出各点到终点的最小距离
void bfs(void) {
point current;
current.x = n - 1;//当前位置
current.y = n - 1;
distances[n - 1][n - 1] = map[n - 1][n - 1];
queue<point>Queue;//建立队列
Queue.push(current);
while (!Queue.empty()) {//当队列非空
current = Queue.front();//头结点出队列
Queue.pop();
point next;
for (int i = 0; i < 4; i++) {
next.x = current.x + direction[i][0];
next.y = current.y + direction[i][1];
if (next.x >= 0 && next.y >= 0 && next.x < n && next.y < n)
if (distances[next.x][next.y] > distances[current.x][current.y] + map[next.x][next.y]) {
distances[next.x][next.y] = distances[current.x][current.y] + map[next.x][next.y];
Queue.push(next);//如果节点满足条件则入队列
}
}
}
}
//dp求出各点到终点的路线总数
__int64 dp(int x,int y){
if(x==n-1&&y==n-1)//如果(x,y)是终点,返回1
return 1;
if(sum[x][y])//该点进行过dp,直接返回
return sum[x][y];
for(int i=0;i<4;i++){
int x2=x+direction[i][0];
int y2=y+direction[i][1];
if(x2>=0&&y2>=0&&x2<n&&y2<n&&distances[x2][y2]<distances[x][y])
sum[x][y]+=dp(x2,y2);
}
return sum[x][y];
}
int main(void) {
while (scanf("%d", &n) != EOF) {
memset(sum,0,sizeof(sum));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
scanf("%d", &map[i][j]);
distances[i][j] = INT_MAX;
}
bfs();
printf("%I64d\n",dp(0,0));
}
return 0;
}