牛客国庆集训派对Day1 C Utawarerumono 扩展欧几里德
#include <stdio.h> #include <algorithm> #include <climits> #include <iostream> #define LL long long using namespace std; const int maxn=1e3+10; #define in(x) scanf("%lld",&x) #define inf 9223372036854775807LL LL ex_gcd(LL a,LL b,LL&x,LL &y) { if(a==0&&b==0) return -1; if(b==0){x=1;y=0;return a;} LL d=ex_gcd(b,a%b,x,y); LL t=x; x=y; y=t-a/b*y; return d; } LL a,b,c; LL p1,p2,q1,q2; LL x_,y_,g,n,m; LL gcd(LL a,LL b) { return b==0? a:gcd(b,a%b); } LL getans(LL x,LL y) { LL r=x*(p2*x+p1)+y*(q2*y+q1); return r; } void getmeow(LL &x,LL &y,LL t) { x=x_+m*t;y=y_-n*t; } int solve1() { int lim=2e3; if(a==0&&b==0) { if(c!=0) { printf("%d\n",5/a); return 0; } LL mx=p1/(p2*-2),my=q1/(q2*-2); //0x+0y==0 LL ans=inf; // cout<<mx-lim<<" "<<mx+lim<<endl; // cout<<getans(-4,-4); for(LL x=mx-lim;x<mx+lim;x++) for(LL y=my-lim;y<my+lim;y++) ans=min(ans,getans(x,y)); printf("%lld\n",ans); return 0; } lim=1e5; if(a==0||b==0) { if(a==0) { if(c%b!=0) { puts("Kuon");return 0; } LL mx=p1/(p2*-2);LL my=c/b; //0x+by=c b!=0 c>=0 LL ans=inf; for(LL x=mx-lim;x<mx+lim;x++) ans=min(ans,getans(x,my)); printf("%lld\n",ans); return 0; } if(b==0) { if(c%a!=0) {puts("Kuon");return 0;} LL mx=c/a,my=q1/(q2*-2); //ax+0y=c LL ans=inf; for(LL y=my-lim;y<my+lim;y++) ans=min(ans,getans(mx,y)); printf("%lld\n",ans); return 0; } } return 1; } void bruce() { long long ans = inf; bool flag = false; for(int i=-100000; i<=100000; i++) { long long y = c - (i*a); if(abs(y) % b == 0) { flag = true; y = y/b; long long nt = p2*i*i + p1*i +q2*y*y + q1*y; if(nt < ans){ ans = nt; cout << ans << " " <<i<< " " << y <<endl; } } else continue; } if(!flag) cout << "Kuon" << endl; else cout << ans<< endl; } int main() { #ifdef shuaishuai freopen("in.txt","r",stdin); #endif // shuaishuai in(a);in(b);in(c); in(p1);in(p2);in(q1);in(q2); // a>0 b>0 c>=0 if(!solve1()) return 0; g=ex_gcd(a,b,x_,y_); m=b/g;n=a/g; if(c%g!=0) { {puts("Kuon");return 0;} } x_*=c/g;y_*=c/g; // printf("%lld %lld %lld\n",x_,y_,a*x_+y_*b); LL ans=inf; // printf("initans:%lld\n",ans); int lim=1e5; LL x=x_,y=y_;int i=0; //两个一元二次函数的加和,求偏导数会发现其极值存在于第三象限 注意求出的特解应化为最小的正整数解 这里我wa到死 LL mx=-1,mi=1; int id=0; while(x>-lim) i--,getmeow(x,y,i); while(x<-lim) i++,getmeow(x,y,i); while(x<=lim) { getmeow(x,y,i); i++; if(getans(x,y)<ans) ans=getans(x,y),id=i; } printf("%lld\n",ans); // printf("myans:%lld %lld %d\n",x,y,id); }