题意:Ax+By=C;求一组解x,y使abs(x)+abs(y)最小,若abs(x)+abs(y)相等,则使(A*abs(x)+B*abs(y))最小
解法:在有解的情况下先得到一组解使x为最小正数,然后分别向上和向下枚举直到x,y异号停止,中间不停更新答案。每次x-dx则y+dy
CODE:
/*扩展欧几里德*/ /*AC代码:0ms*/ #include <iostream> #include <cstdio> #include <algorithm> #include <memory.h> #include <cmath> using namespace std; int A,B,C; int ans_x,ans_y,Min; int extgcd(int a,int b,int &x,int &y) { if(b==0) {x=1;y=0;return a;} int d=extgcd(b,a%b,x,y); int t=x;x=y;y=t-a/b*y; return d; } int main() { int w,dx,dy,X,Y,x,y,temp; while(scanf("%d%d%d",&A,&B,&C)!=EOF) { if(A==0&&B==0&&C==0) break; w=extgcd(A,B,X,Y); if(C%w) printf("no solution\n"); else { X*=C/w; dx=B/w; dy=A/w; X=(X%dx+dx)%dx; Y=(C-A*X)/B; ans_x=abs(X);ans_y=abs(Y); Min=abs(X)+abs(Y); //printf("@%d %d %d %d\n",X,Y,dx,dy); //从X,Y开始上下枚举,直到x,y异号 x=X;y=Y; while(true)//向上枚举 { if(x>0&&y<0) break; x+=dx;y-=dy; temp=abs(x)+abs(y); if(temp<Min)//更新答案 { ans_x=abs(x); ans_y=abs(y); Min=temp; } else if(temp==Min) { if((A*abs(x)+B*abs(y))<(A*ans_x+B*ans_y)) { ans_x=abs(x); ans_y=abs(y); } } } x=X;y=Y; while(true)//向下枚举 { if(x<0&&y>0) break; x-=dx;y+=dy; temp=abs(x)+abs(y); if(temp<Min)//更新答案 { ans_x=abs(x); ans_y=abs(y); Min=temp; } else if(temp==Min) { if((A*abs(x)+B*abs(y))<(A*ans_x+B*ans_y)) { ans_x=abs(x); ans_y=abs(y); } } } printf("%d %d\n",ans_x,ans_y); } } return 0; }