遇到一道扩展欧几里得题(个人觉得)
但是他们说是同余最短路问题 ,我不知道这个算法,以后在学吧。
题目:https://ac.nowcoder.com/acm/contest/4853/D
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 using ll = long long; 5 void exgcd(ll a, ll b, ll &x, ll &y){ 6 if(b == 0){ 7 x = 1, y = 0; 8 return; 9 } 10 exgcd(b,a%b,x,y); 11 ll t = x; 12 x = y; 13 y = t - (a/b) * y; 14 } 15 ll gcd(ll a, ll b){ 16 return b == 0?a:gcd(b,a%b); 17 } 18 int main(){ 19 ll a, b, c, k; 20 cin >> a >> b >> c >> k; 21 ll e = gcd(a,b); 22 for(int i = 0; i <= k /c; ++ i){ 23 ll d = k - i*c, x, y; 24 if(d%e)continue; 25 exgcd(a,b,x,y); 26 ll n = d/e; 27 ll m = b/e; 28 x *= n, y *= n;//还原 29 x = (x%m + m) % m;//变为正数; 30 y = (d - x * a)/b; 31 if(x>=0 && y >= 0){//保证大于零 32 cout << x << " " << y << " " << i << endl; 33 break; 34 } 35 } 36 return 0; 37 }
追求吾之所爱