POJ 1061
题意:
两只青蛙在同一条纬度上,它们各自朝西跳,问它们要跳多少步才能碰面(必须同时到达同一点).
分析:
假设它们跳了t步才相遇,青蛙a初始坐标为x,青蛙b初始坐标为y,则跳了t步相遇后a的坐标为 x+m*t-p1*l, b的坐标为 y+n*t-p2*l (p1,p2分别表示a,b跳
的圈数) x+m*t-p1*l = y+n*t-p2*l => x-y = (n-m)*t + (p1-p2)*l => x-y = (n-m)*t + p*l.
代码如下:
1 //方法一
2
3
4 #include <iostream>
5 #include <cstdio>
6 #include <cstring>
7 #include <fstream>
8 #include <ctime>
9 #include <cmath>
10 #include <cstdlib>
11 #include <algorithm>
12 #include <set>
13 #include <map>
14 #include <list>
15 #include <stack>
16 #include <queue>
17 #include <iterator>
18 #include <vector>
19
20 using namespace std;
21
22 #define LL long long
23 #define INF 0x3f3f3f3f
24 #define MOD 1000000007
25 #define MAXN 10000010
26 #define MAXM 1000010
27
28
29 LL extend_gcd(LL a, LL b, LL &x, LL &y)
30 {
31 if(b == 0)
32 {
33 x = 1;
34 y = 0;
35 return a;
36 }
37 else
38 {
39 LL r = extend_gcd(b, a%b, y, x);
40 y -= x*(a/b);
41 return r;
42 }
43 }
44
45
46 int main()
47 {
48 LL x, y, m, n, l;
49 while(scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &l)==5)
50 {
51 LL t, p;
52 LL ans = extend_gcd(n-m, l, t, p);
53 if((x-y)%ans)
54 printf("Impossible\n");
55 else
56 {
57 t = t*(x-y)/ans;
58 t = (t%(l/ans)+(l/ans))%(l/ans);
59 printf("%lld\n", t);
60 }
61 }
62
63 return 0;
64 }
1 //方法二
2
3
4 #include <iostream>
5 #include <cstdio>
6 #include <cstring>
7 #include <fstream>
8 #include <ctime>
9 #include <cmath>
10 #include <cstdlib>
11 #include <algorithm>
12 #include <set>
13 #include <map>
14 #include <list>
15 #include <stack>
16 #include <queue>
17 #include <iterator>
18 #include <vector>
19
20 using namespace std;
21
22 #define LL long long
23 #define INF 0x3f3f3f3f
24 #define MOD 1000000007
25 #define MAXN 10000010
26 #define MAXM 1000010
27
28
29 LL extend_gcd(LL a, LL b, LL &x, LL &y)
30 {
31 if(b == 0)
32 {
33 x = 1;
34 y = 0;
35 return a;
36 }
37 else
38 {
39 LL r = extend_gcd(b, a%b, y, x);
40 y -= x*(a/b);
41 return r;
42 }
43 }
44
45
46 LL cal(LL a, LL b, LL c)
47 {
48 LL x, y;
49 LL ans = extend_gcd(a, b, x, y);
50 if(c%ans)
51 return -1;
52 x *= c/ans;
53 b /= ans;
54 if(b < 0)
55 b = b*(-1);
56 // b = abs(b); //abs只能对int取绝对值
57 ans = x%b;
58 if(ans <= 0)
59 ans += b;
60 return ans;
61 }
62
63 int main()
64 {
65 LL x, y, m, n, l;
66 while(scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &l)==5)
67 {
68 LL sum = cal(n-m, l, x-y);
69 if(sum == -1)
70 printf("Impossible\n");
71 else
72 printf("%lld\n", sum);
73 }
74
75 return 0;
76 }