Romantic HDU - 2669(扩展欧几里得)

Romantic

题目链接:HDU - 2669
题意:求出a*x+b*y=1的一个x为最小的非负数的解;无解输出sorry;
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
long long exgcd(long long a, long long b, long long &x, long long &y){
	if(b==0){
		x=1, y=0;
		return a;
	}
	long long r=exgcd(b, a%b, x, y);
	long long t=x;
	x=y;
	y=t-a/b*y;
	return r;
}
int main(){
	long long a, b, x, y;
	while(cin >> a >> b){
		if(exgcd(a, b, x, y)==1){	
			if(x<0) x+=b, y-=a;//x是非负数, 最小;
			cout << x << ' ' << y << endl;
		}
		else cout << "sorry\n"; 
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/sirius_han/article/details/80048079