SGU141 Jumping Joe
题目大意
有只青蛙在x轴原点,要刚好K步跳到坐标为P的点上
每次可以向左或向右跳x1或x2的距离,构造跳的方式,不存在则输出“NO”
算法思路
对于同样的跳跃距离,向左跳与向右跳互相抵消,因此每种跳跃只会朝一个方向
假设跳了a次x1,跳了b次x2,正值向右,负值向左
则该问题为求解方程 a * x1 + b * x2 = P,考察参数t满足 | t | <= | P | + 1 的所有解
求出a、b后,考察a、b绝对值之和与K是否相差为偶数,是的话剩下的步数,可以一左一右跳完
时间复杂度: O(P)
代码
/**
* Copyright © 2015 Authors. All rights reserved.
*
* FileName: 141.cpp
* Author: Beiyu Li <sysulby@gmail.com>
* Date: 2015-06-17
*/
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define For(i,s,t) for (int i = (s); i <= (t); ++i)
#define foreach(i,c) for (__typeof(c.begin()) i = c.begin(); i != c.end(); ++i)
typedef long long LL;
typedef pair<int, int> Pii;
const int inf = 0x3f3f3f3f;
const LL infLL = 0x3f3f3f3f3f3f3f3fLL;
void gcd(LL a, LL b, LL &g, LL &x0, LL &y0)
{
if (!b) g = a, x0 = 1, y0 = 0;
else gcd(b, a % b, g, y0, x0), y0 -= x0 * (a / b);
}
LL a, b, c, k;
bool calc(LL x, LL y)
{
LL t = abs(x) + abs(y);
if (t > k || ((k - t) & 1)) return false;
puts("YES");
k = (k - t) / 2;
if (x >= 0) printf("%lld %lld ", x + k, k);
else printf("%lld %lld ", k, -x + k);
if (y >= 0) printf("%lld %lld\n", y, 0LL);
else printf("%lld %lld\n", 0LL, -y);
return true;
}
bool solve()
{
LL g, x0, y0;
gcd(a, b, g, x0, y0);
if (c % g) return false;
a /= g, b /= g, c /= g;
For(t,-abs(c)-1,abs(c)+1)
if (calc(x0 * c + b * t, y0 * c - a * t)) return true;
return false;
}
int main()
{
scanf("%lld%lld%lld%lld", &a, &b, &c, &k);
if (!solve()) puts("NO");
return 0;
}