Darkgy is a transport pipe master. One day, due to some strange redstone signal, an Iron pipe changed its direction and make a part of the pipe system become a circulation pipe.
The circulation pipe consists of L unit pipe numbered from 0 to L-1. Every K ticks, an item will input into pipe 0, and it will be transported in pipes with 1 unit pipe length per tick speed from pipe 0 to pipe L-1. When it was transported into pipe L-1, its direction will reversed and will be transported from L-1 to 0. When it reached pipe 0, its direction will be reversed again.
This process will repeat until the moment when there are more than C items in one of the L pipes, C is the capacity of each pipe.
For example, if L=5, K=3, C=1.
In tick 0, the first item will input into pipe 0.
In tick 3, it will be transported into pipe 3 and the second item will input into pipe 0.
In tick 4, the first item reached pipe 4 and its direction reversed, at the same time, the second item moved into pipe 1.
In tick 6, the third item appeared in pipe 0, the first item moved into pipe 2 while the second item was in pipe 3. Though the first item and the second item crossed, but......it does not matter XD.
In tick 7, the first item and the third item meet in pipe 1, and pipe 1 blast.
Darkgy want to know in which tick, the circulation pipe will blast.
There are large amount of test cases, for each test case, there will be only one line with 3 integers 1 ≤ L, K, C ≤ 104 which was mentioned in the description.
For each test case, you should output only one line with an integer T which means the tick when circulation pipe was blast.
5 3 1 1 1 1 1 1 2 1 1 3
7 1 2 3
用扩展gcd求解,详见代码
#include <bits/stdc++.h> using namespace std; typedef long long ll; template<class T> inline bool scan_d(T &ret){ char c; ret = 0; if(c=getchar(),c==EOF) return 0; while(c<'0' || c>'9') c=getchar(); while(c>='0'&&c<='9') ret = ret*10 + (c-'0'),c=getchar(); return 1; } void exgcd(int a, int b, int& d, int& x, int& y){ if(!b) {d=a; x=1; y=0;} else {exgcd(b, a%b, d, y, x); y -= x*(a/b);} } int main(){ int L, K, C; int x, y, d; int L2, M, T, x2; ll ans, tmp; while(true){ if(scan_d(L)==0) break; scan_d(K); scan_d(C); if(L==1){ printf("%lld\n", (ll)K*C); continue; } L--; L2=L<<1; exgcd(K, L2, d, x, y); M = L2/d; T = L2*K/d;//最靠近的两个在同一点同向的时间差 ans = (ll)T*C;//0和L-1点的情况只能都是同向的 for(int i=1; i<L; ++i){//枚举中间的2..L-2的情况 if((i*2)%d) continue; //无解,不可能在i相遇 tmp = i; tmp += (ll)T*(C>>1); //因为同向的两个之间必定还有一个反向的 if(C&1){//为C奇数则还需要一个反向的 x2 = x*(L-i)*2/d; x2 -= x2/M*M; if(x2<=0) x2 += M; x2 *= K; tmp += x2; } if(tmp<ans) ans = tmp; } printf("%lld\n", ans); } return 0; }