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
ACM暑期集训队练习赛(三)
- 害,(恰一口柠檬水),这题也太难了吧
- 又是优先队列又是记忆化搜索
- 先用bfs查出每个点到终点的最优解,当然是从终点开始找
- 然后dfs一个一个跑,找比当前位置的数小的值
- 下了大概2个小时,中间重写了一遍,我太菜了
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<math.h>
#include<string.h>
#include<sstream>
using namespace std;
int n;
int a[55][55];
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
struct q1{
int x, y, ans;
};
struct cmp{
bool operator() (q1 &a, q1 &b){
return a.ans > b.ans;
}
};
void bfs(){
int vis[55][55] = {0};//别问为什么放这里,问就是我喜欢
priority_queue<q1,vector<q1>,cmp> p;
p.push({n,n,a[n][n]});
vis[n][n] = 1;
while(!p.empty()){
int x = p.top().x;
int y = p.top().y;
int ans = p.top().ans;
p.pop();
for(int i = 0; i < 4; i ++){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 1 || ty < 1 || tx > n || ty > n)continue;
if(vis[tx][ty] == 1)continue;
vis[tx][ty] = 1;
int tans = ans + a[tx][ty];
a[tx][ty] = tans;//最优解要存好
p.push({tx,ty,tans});
}
}
}
long long ans[55][55];
long long dfs(int x, int y){
if(x == n && y == n)return 1;
if(ans[x][y] != -1)return ans[x][y];
ans[x][y] = 0;
for(int i = 0; i < 4; i ++){
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 1 || ty < 1 || tx > n || ty > n)continue;
// 找比当前位置小的数,一定有路
if(a[x][y] > a[tx][ty])ans[x][y] += dfs(tx,ty);
}
return ans[x][y];
}
int main() {
//ios::sync_with_stdio(false);
while(~scanf("%d",&n)){
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= n; j ++)
cin >> a[i][j];
}
bfs();
memset(ans,-1,sizeof(ans));
cout << dfs(1,1) << endl;
}
return 0;
}