2020ICPC上海L Traveling in the Grid World

题目链接

题意:

有一个 ( n + 1 ) × ( m + 1 ) (n+1)\times (m+1) (n+1)×(m+1)的网格图,从上到下 0... n 0...n 0...n,从左到右 0... m 0...m 0...m,现在要从 ( 0 , 0 ) (0,0) (0,0)点走到 ( n , m ) (n,m) (n,m)点,满足每次只能走到一个整点,路径为两点连成的直线段,这条线段上不能有其他整点,两点之间的路程即这条线段的长度(欧几里得距离),且不能连续两次往同一方向走,问最短的路程。
( 1 ≤ n , m ≤ 1 0 6 ) (1 \le n,m \le 10^6) (1n,m106)

题解:

如果 gcd ⁡ ( n , m ) = 1 \gcd(n,m)=1 gcd(n,m)=1,那么可以直接从 ( 0 , 0 ) (0,0) (0,0)走到 ( n , m ) (n,m) (n,m)
如果 gcd ⁡ ( n , m ) ≠ 1 \gcd(n,m) \ne 1 gcd(n,m)=1,那么肯定需要走折线。可以发现如果走了超过2条的折线,那么在不考虑每一步的路径上无整点的限制条件下,可以用“三角形两边之和大于第三边”将折线变成直线,最后会变成只剩2条折线(一个拐点),但是这两条折线是不一定满足要求的。可以发现两条折线中长度最小的那种方案是可以满足路径上无整点限制的,假设起点为 A A A,终点为 B B B,拐点为 C C C,那么 A C + C B AC+CB AC+CB是长度最小的,如果不满足,假设 A C AC AC上有一个整点 D D D,那么 A D + D B < A C + C B AD+DB<AC+CB AD+DB<AC+CB,因为 D B < D C + C B DB<DC+CB DB<DC+CB,那么 A C + C B AC+CB AC+CB就不是长度最小的了,矛盾。由以上可以推出超过2条折线的方案不会是最优方案,且最优方案就是两条折线的方案中长度最小的那个。下面考虑怎么找到这个方案,遍历 0... n 0...n 0...n,那么对于每一行,有可能的拐点只能是靠 ( 0 , 0 ) − ( n , m ) (0,0)-(n,m) (0,0)(n,m)这条线段最近的左右两个点,因为这一行上其他的点都可以用“三角形两边之和大于第三边”给排除掉。

复杂度: O ( n ) O(n) O(n)
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<bitset>
#include<sstream>
#include<ctime>
//#include<chrono>
//#include<random>
//#include<unordered_map>
using namespace std;

#define ll long long
#define ls o<<1
#define rs o<<1|1
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define sz(x) (int)(x).size()
#define all(x) (x).begin(),(x).end()
const double pi=acos(-1.0);
const double eps=1e-6;
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
ll read(){
	ll x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
int T,n,m;
int gcd(int a,int b){
	if(b==0){
		return a;
	}
	return gcd(b,a%b);
}
double dis(int x,int y,int nx,int ny){
	return sqrt(1ll*(x-nx)*(x-nx)+1ll*(y-ny)*(y-ny));
}
double ans;
void solve(int r,int c){
	if(r<0||r>n||c<0||c>m)return;
	if(1ll*c*n==1ll*m*r)return;
	if(gcd(r,c)==1&&gcd(n-r,m-c)==1){
		ans=min(ans,dis(0,0,r,c)+dis(r,c,n,m));
	}
}
int main(void){
	// freopen("in.txt","r",stdin);
	scanf("%d",&T);
	while(T--){
		scanf("%d%d",&n,&m);
		if(gcd(n,m)==1){
			printf("%.15f\n",dis(0,0,n,m));
			continue;
		}
		ans=1e18;
		for(int i=0;i<=n-1;i++){
			int p;
			int t=1ll*(n-i)*m/n;
			p=m-t;
			solve(i,p);
			solve(i,p+1);
			solve(i,p-1);
		}
		printf("%.15f\n",ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值