Codeforces 1807F

Problem Link

The simple brute force method of manually implementing each bounce is sufficient to solve the problem, if we can prove that the ball will bound no more than O ( n + m ) \mathcal O (n+m) O(n+m) times

If you start enumerating each bounce, you will notice that the ball will end up in no more than 2 ⋅ ( n + m ) 2\cdot (n+m) 2(n+m) places after one bounce, since they can only bounce at the border of the grid. Moreover, since the ball only goes in the diagonal direction, the ball only has two possible directions when it hits the wall (parallel to the main diagonal or the secondary diagonal), meaning that the ball only has 4 ⋅ ( n + m ) 4\cdot (n+m) 4(n+m) possible states.

With this conclusion, we can be sure that the ball will bounce for at most 4 ⋅ n ⋅ m 4\cdot n \cdot m 4nm times before it hits the objective (assuming feasibility). Then, the rest can be done with ad-hoc enumeration that ends when the bounce count exceeds the deduced limit.

Time Complexity: O ( 4 ⋅ ( n + m ) ) \mathcal O(4 \cdot (n + m)) O(4(n+m))

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int dx[]={-1,1};
const int dy[]={-1,1};
int n,m,sx,sy,ex,ey,u,v;
inline int read()
{
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0' || ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
bool move(int &x,int &y,int &u,int &v)
{
	while(x+dx[u]>=1 && x+dx[u]<=n && y+dy[v]>=1 && y+dy[v]<=m)
	{
		x+=dx[u],y+=dy[v];
		if(x==ex && y==ey)return true;
	}
	if(!(x+dx[u]>=1 && x+dx[u]<=n))u^=1;
	if(!(y+dy[v]>=1 && y+dy[v]<=m))v^=1;
	return false;
}
int main()
{
	// freopen("in.txt","r",stdin);
	int T=read();
	while(T--)
	{
		n=read(),m=read();
		sx=read(),sy=read();
		ex=read(),ey=read();
		char s[5];
		scanf("%s",s);
		u=(s[0]=='D');
		v=(s[1]=='R');
		int ans=0;
		for(int i=1;i<=5*(n+m);++i)
		{
			if(sx==ex && sy==ey){printf("%d\n",ans);goto GG;}
			if(move(sx,sy,u,v)){printf("%d\n",ans);goto GG;}
			++ans;
		}
		puts("-1");
		GG:;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值