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