CodeForces - 724C Ray Tracing(扩展欧几里得解方程)
題目鏈接:點(diǎn)擊查看
題目大意:在 n?mn*mn?m 的矩陣中,從點(diǎn) (0,0)(0,0)(0,0) 發(fā)射一個(gè)小球,以四十五度的方向出發(fā),速度是 2\sqrt{2}2?,當(dāng)碰到壁時(shí),會(huì)進(jìn)行反射;當(dāng)碰到底角時(shí),會(huì)被吸收。現(xiàn)在給出 kkk 次詢問,每次詢問需要回答點(diǎn) (x,y)(x,y)(x,y) 是在什么時(shí)間第一次到達(dá),如果無法到達(dá)輸出 ?1-1?1
題目分析:模擬也是可以做的,同樣也可以從數(shù)論的角度去思考
考慮將矩形進(jìn)行平面無限展開后,每一個(gè)點(diǎn) (x,y)(x,y)(x,y) 都可以被表示為 (2?n?k1±x,2?m?k2±y)(2*n*k_1 \pm x,2*m*k_2 \pm y)(2?n?k1?±x,2?m?k2?±y),其中 k1k_1k1? 表示的是穿過了多少條平行于 xxx 軸的邊,k2k_2k2? 表示的是穿過了多少條平行于 yyy 軸的邊,因?yàn)樵诒绢}中速度是 45°45\degree45°,所以最終 xxx 和 yyy 坐標(biāo)在無限展開后一定是相等的,顯然有 2?n?k1±x=2?m?k2±y2*n*k_1 \pm x = 2*m*k_2 \pm y2?n?k1?±x=2?m?k2?±y,移項(xiàng)得到 2?n?k1?2?m?k2=±y?±x2*n*k_1-2*m*k_2=\pm y - \pm x2?n?k1??2?m?k2?=±y?±x
然后將 (x,y)(x,y)(x,y) 分四種情況,分別用擴(kuò)展歐幾里得求一下最小正整數(shù)解維護(hù)答案的最小值就好了
需要注意的是,當(dāng)時(shí)間大于等于 lcm(n,m)lcm(n,m)lcm(n,m) 后會(huì)被吸收,需要特判一下
代碼:
// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<unordered_map> using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; LL ans,limit; LL n,m,k; template<class T> void exgcd(T a,T b,T &d,T &x,T &y){if(!b) {d=a;x=1;y=0;}else {exgcd(b,a%b,d,y,x);y-=x*(a/b);} } //求解二元一次方程 a*x+b*y=c,一組解為x,y,無解則返回false template<class T> bool Solve_equation(T a,T b,T c,T &x,T& y){T gcd;exgcd(a,b,gcd,x,y);if(c%gcd) return false; //無解T k=c/gcd;x*=k;y*=k;T xplus=b/gcd,yplus=a/gcd; if(xplus<0) xplus*=-1;if(yplus<0) yplus*=-1;//此時(shí)求出的x,y即為一組解,該方程的通解形式為X=x+t*(b/gcd),Y=y-t*(a/gcd) t為任意正整數(shù)//根據(jù)題目要求我們需要構(gòu)造特殊解x=(x%xplus+xplus)%xplus;y=(c-a*x)/b; //x的最小正整數(shù)解//y=(y%yplus+yplus)%yplus;x=(c-b*y)/b; //y的最小正整數(shù)解return true; } void solve(LL dx,LL dy) {LL k1,k2;if(!Solve_equation(2*n,-2*m,dy-dx,k1,k2)) return;LL res=2*n*k1+dx;if(res>=limit) return;if(ans==-1||res>=0&&ans>res) ans=res; } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);read(n),read(m),read(k);limit=n*m/__gcd(n,m);while(k--){int x,y;read(x),read(y);ans=-1;solve(x,y),solve(x,-y),solve(-x,y),solve(-x,-y);write(ans),putchar('\n');}return 0; }總結(jié)
以上是生活随笔為你收集整理的CodeForces - 724C Ray Tracing(扩展欧几里得解方程)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客 - Pass Through Wi
- 下一篇: Java中关于Arrays.sort的两