题意:两只青蛙初始在数轴的x,y点,单位时间内分别可以向右跳m米和n米,数轴是环型的,长度为L,问两只青蛙能否相遇,以及相遇时跳的次数。
思路:相遇就是同一时间在同一地点。
那么有方程 x+ C*m = y + C*n + k*L 其中C为跳的次数,k为之间差了L的个数(可以理解为被套圈的圈数)
化简得到 C(m-n) + K*L = y-x.
根据裴蜀定理,该方程有解,当且仅当y-x是gcd(m-n,L)的倍数。
然后根据扩展欧几里得算法,需要注意的是其中可能有负数。
如果a是负数,可以把问题转化成
(
为a的绝对值),然后令
。
第二个需要注意的是,扩展欧几里得算法求出的是ax+by=gcd(a,b)的解,x,y还要乘对应的倍数才能得到正确的解。
第三个需要注意的是,跳的次数一定为正,这是隐含条件。
用了上道题用的while去得到第一个大于0的X会TLE
所以其实 X = ( X % gx + gx) %gx就好。。。? (其中gx = b/gcd(a,b))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
/* *********************************************** Author :111qqz Created Time :Wed 12 Oct 2016 08:43:02 PM CST File Name :code/poj/1061.cpp ************************************************ */ #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #define fst first #define sec second #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define ms(a,x) memset(a,x,sizeof(a)) typedef long long LL; #define pi pair < int ,int > #define MP make_pair using namespace std; const double eps = 1E-8; const int dx4[4]={1,0,0,-1}; const int dy4[4]={0,-1,1,0}; const int inf = 0x3f3f3f3f; LL x,y,m,n,L; LL exgcd( LL a,LL b, LL &x,LL &y) { if (b==0) { x = 1LL; y = 0LL; return a; } LL ret = exgcd(b,a%b,x,y); LL tmp = x; x = y; y = tmp - a/b*y; return ret; } int main() { #ifndef ONLINE_JUDGE freopen("code/in.txt","r",stdin); #endif cin>>x>>y>>m>>n>>L; LL tmp1 = y-x; LL tmp2 = m-n; /* LL X,Y,GCD; GCD = exgcd(tmp2,L,X,Y); if (tmp1%GCD) puts("Impossible"); else { X = X * (tmp1/GCD); LL gx = L/GCD; if (gx<0) gx = - gx; X = (X%gx +gx)%gx; printf("%lld\n",X); } */ if (tmp1<0) { tmp1 = -tmp1; tmp2 = -tmp2; } LL X,Y; LL GCD; if (tmp2<0) { GCD = exgcd(-tmp2,L,X,Y); X = -X; } else { GCD = exgcd(tmp2,L,X,Y); } if (tmp1%GCD) { puts("Impossible"); } else { LL gx = L/GCD; X = X * tmp1/GCD; X = (X % gx + gx) % gx; printf("%lld\n",X); } #ifndef ONLINE_JUDGE fclose(stdin); #endif return 0; } |
说点什么
您将是第一位评论人!