一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情。
题目
780.到达终点
题目大意
给定四个整数 sx , sy ,tx 和 ty,如果通过一系列的转换可以从起点 (sx, sy) 到达终点 (tx, ty),则返回 true,否则返回 false。
从点 (x, y) 可以转换到 (x, x+y) 或者 (x+y, y)。
样例
示例 1:
输入: sx = 1, sy = 1, tx = 3, ty = 5
输出: true
解释:
可以通过以下一系列转换从起点转换到终点:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
示例 2:
输入: sx = 1, sy = 1, tx = 2, ty = 2
输出: false
示例 3:
输入: sx = 1, sy = 1, tx = 1, ty = 1
输出: true
数据规模
提示:
思路
考虑终点状态的上一个状态:或者,因为,所以必须分别保证或者。那么对于之间的关系,考虑三种情况:
- :则必然上一状态会有状态,所以此时就是起点状态(即不存在上一状态),那么要想满足条件,必须有;
- :则上一状态为
- :则上一状态为
所以从终点状态进行回推状态是固定的,而由起点状态往后推则是不固定的。
由于每一步反向操作一定是将和中的较大的值减小,比如:可以直接把更新到比小,即;:可以直接把更新到比小,即。
当反向操作的条件不成立时,根据和的不同情况分别判断是否可以从起点转换到终点:
- :满足条件;
- :只有当且 时可以从起点转换到终点。
- :只有当且 时可以从起点转换到终点。
- 其余的都不满足条件。
代码
// short int long float double bool char string void
// array vector stack queue auto const operator
// class public private static friend extern
// sizeof new delete return cout cin memset malloc
// relloc size length memset malloc relloc size length
// for while if else switch case continue break system
// endl reverse sort swap substr begin end iterator
// namespace include define NULL nullptr exit equals
// index col row arr err left right ans res vec que sta
// state flag ch str max min default charray std
// maxn minn INT_MAX INT_MIN push_back insert
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
typedef pair<int, string>PIS;
const int maxn=3e4+50;//注意修改大小
long long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}
ll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while(tx>sx&&ty>sy&&tx!=ty){
if(tx>ty){
tx%=ty;
}
else{
ty%=tx;
}
}
if (sx == tx && sy == ty){
return 1;
}
if (tx == sx)
{
if (ty == sy || (ty - sy) % tx == 0)
return 1;
}
if (ty == sy)
{
if (tx == sx || (tx - sx) % ty == 0)
return 1;
}
return 0;
}
};