uvaoj 12169 Disgruntled Judge 擴展歐幾里得算法

uvaoj 12169 Disgruntled Judge 擴展歐幾里得算法
一個裁判,找了3個整數x1,a和b,按照遞推公式xi=(axi-1+b)%10001,計算出了一個長度爲2n的序列,n是測試數據的組數,然後他把n和x1,x3,。。。,x2n-1寫到輸入文件中,x2,x4,。。。,x2n寫到輸出文件中。你的任務是找出對應的x2,x4,。。。,x2n。任意輸出一個合法的。
如果知道了a,根據x2=(ax1+b)%10001,x3=(ax2+b)%10001,聯立可以得到x3=(a((ax1+b)%10001) + b)%10001=(a(ax1+b)+b)%10001也就是,x3+10001k=(a+1)b+a*a*x1.
可以寫成(a+1)b+10001(-k)=x3-a*a*x2,這是不定方程的形式,可以用擴展歐幾里得算法求出b。枚舉a,求出b,然後求出整個序列,判斷序列是否合法就可以了。複雜度爲10^6。
代碼如下:
/*************************************************************************
	> File Name: 12169.cpp
	> Author: gwq
	> Mail: [email protected] 
	> Created Time: 2015年01月21日 星期三 20時08分53秒
 ************************************************************************/

#include <cmath>
#include <ctime>
#include <cctype>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>

#define INF (INT_MAX / 10)
#define clr(arr, val) memset(arr, val, sizeof(arr))
#define pb push_back
#define sz(a) ((int)(a).size())

using namespace std;
typedef set<int> si;
typedef vector<int> vi;
typedef map<int, int> mii;
typedef long long ll;
typedef unsigned long long ull;

const double esp = 1e-5;

#define N 110

ll num[N];

void exgcd(ll a, ll b, ll &d, ll &x, ll &y)
{
	if (!b) {
		d = a;
		x = 1;
		y = 0;
	} else {
		exgcd(b, a % b, d, y, x);
		y -= x * (a / b);
	}
}

int main(int argc, char *argv[])
{
	ll n;
	scanf("%lld", &n);
	for (ll i = 1; i <= n; ++i) {
		scanf("%lld", &num[2 * i - 1]);
	}
	for (ll a = 0; a <= 10000; ++a) {
		ll d, x, y, t, b;
		exgcd(a + 1, 10001, d, x, y);
		t = num[3] - a * a * num[1];
		if (t % d) {
			continue;
		}
		x *= t / d;
		y *= t / d;
		b = x;
		ll flag = 0;
		for (ll i = 2; i <= 2 * n; ++i) {
			ll tmp = (a * num[i - 1] + b) % 10001;
			if (i % 2 == 0) {
				num[i] = tmp;
			} else {
				if (num[i] != tmp) {
					flag = 1;
					break;
				}
			}
		}
		if (!flag) {
			break;
		}
	}
	for (ll i = 1; i <= n; ++i) {
		printf("%lld\n", num[2 * i]);
	}

	return 0;
}

參考:http://blog.csdn.net/u013451221/article/details/38497029
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章