跳到正文

题解

P9107 [PA2020] Wycieczka górska 题解

makerli约 6 分钟
原文
文章信息与版本

文章信息

发布
2024年6月8日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 6 分钟
题目
P9107

版本

  1. v2当前
  2. v1

link

一道非常有趣的广搜题,把蒟蒻卡了两周半。

#1 (30pts)

不难想到,对于每个旅行者都运行一次广搜,然后比较出最快的路线,这样可以光荣地骗到30分。

code:

C++
#include<bits/stdc++.h>
#define int long long	//不开long long见祖宗
using namespace std;
char mp[202][2002];
bool flag[2002][2002];
//方位数组
int fx[5]= {0,1,-1,0,0};
int fy[5]= {0,0,0,1,-1};
int n,m,k;
struct zt {
	int x,y,step;
};
queue<zt>q;
int bfs(int a,int b) {	//广搜
	int ans=11451419198101145;
	q.push({1,1,0});
	while(!q.empty()) {
		zt now=q.front();
		q.pop();
		if(now.x==n&&now.y==m) {	//边界
			ans=min(ans,now.step);
			continue;
		}
		for(int i=1; i<=4; i++) {
			int tx=now.x+fx[i],ty=now.y+fy[i];
			if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&!flag[tx][ty]&&mp[tx][ty]=='.')
				if(i&1==1) {
					flag[tx][ty]=1;
					q.push({tx,ty,now.step+a});
				} else {
					flag[tx][ty]=1;
					q.push({tx,ty,now.step+b});
				}
		}
	}
	memset(flag,0,sizeof(flag));	//多测要清空
	return ans;
}
signed main() {
	//输入输出优化
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	int ta,tb,cnt=1,ans=11451419198101145;
	cin>>n>>m>>k;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++)
			cin>>mp[i][j];
	for(int i=1; i<=k; i++) {
		cin>>ta>>tb;
		int t=bfs(ta,tb);
		if(ans==t)
			cnt++;
		if(t<ans)
			ans=t,cnt=1;
	}
	cout<<ans<<' '<<cnt;
	return 0;
}

#2 (100pts)

不难发现,其实每个人走的最短路线都是一样的,所以只需通过一次广搜即可搜出所有旅行者的上山最短路径,然后比较每个人的用时即可求出答案。

在计算最短路径时,要注意:由于每下山一次都要上一次山补回来,所以当总路程相同时,下山次数少的方案更优。

“每个人走的最短路线都是一样的”证明:设上山的次数为 xx,下山的次数为 yy,那么一个人的用时即为 x⋅a+y⋅bx \cdot a +y \cdot b。因为 a,ba,b 都大于0,所以 x,yx,y 越小,用时就越少。

code:

C++
#include<bits/stdc++.h>
#define int long long	//不开long long见祖宗
using namespace std;
char mp[2002][2002];
bool flag[2002][2002]
int fx[5]= {0,1,-1,0,0};
int fy[5]= {0,0,0,1,-1};
int n,m,k;
struct zt {
	int x,y,up,down;
	bool operator <(const zt &a) const {	//重载运算符,比较最短步数。当步数相同时,下山次数少的总时长更少
		if(a.up+a.down!=up+down)
			return up+down<a.up+a.down;
		else
			return up<a.up;
	}
};
queue<zt>q;
signed main() {
	//输入输出优化
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	int a,b,cnt=0,sum=114514191981011145,t;
	zt ans= {0,0,11451419198101145,11451419198101145};
	cin>>n>>m>>k;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++)
			cin>>mp[i][j];
	q.push({1,1,0,0});
	flag[1][1]=1;
	while(!q.empty()) {	//广搜
		zt now=q.front();
		q.pop();
		if(now.x==n&&now.y==m) {
			ans=min(ans,now);
			continue;
		}
		for(int i=1; i<=4; i++) {
			int tx=now.x+fx[i],ty=now.y+fy[i];
			if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&!flag[tx][ty]&&mp[tx][ty]=='.')
				if(i%2==1) {
					flag[tx][ty]=1;
					q.push({tx,ty,now.up+1,now.down});
				} else {
					flag[tx][ty]=1;
					q.push({tx,ty,now.up,now.down+1});
				}
		}
	}
	for(int i=1; i<=k; i++) {
		cin>>a>>b;
		t=ans.up*a+ans.down*b;	//计算用时
		if(t<sum)
			sum=t,cnt=0;
		if(t==sum)
			cnt++;
	}
	cout<<sum<<' '<<cnt;
	return 0;
}
原文