Disgruntled Judge UVA - 12169(扩展欧几里德+暴力)

题目链接:

https://vjudge.net/problem/UVA-12169

题意:

有3个整数 x[i], a, b 满足递推式x[i]=(a*x[i-1]+b)mod 10001。由这个递推式计算出了长度为2T的数列,现在要求输入x[1],x[3],......x[2T-1], 输出x[2],x[4]......x[2T]. T<=100,0<=x<=10000. 如果有多种可能的输出,任意输出一个结果即可。

题解:

1、列出公式:


x2 = (ax1 + b) % 10001; ······ ①
x3 = (ax2 + b) % 10001; ······ ②
把①带入②得:
x3 = (a( ax1 + b) % 10001 ) + b) % 10001;
=》 x3 = (a*a*x1 + a*b+ b) % 10001;
=》 x3 -  (a*a*x1 + a*b+ b) = 10001*y;
=》 x3 - a*a*x1  = (a + 1) * b + 10001 * y;
=》(a + 1) * b + 10001 * y = x3 - a*a*x1;
看作:ax + by = c 的形式。


2、用欧几里德算法求解:


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

解释参数: a, b 是系数,d 为a与b的最大公约数,x与y是解。

现在对于方程(a + 1) * b + 10001 * y = x3 - a*a*x1,想求出b需要知道a,但是知道a的取值范围是0~10000,所以暴力枚举就好,枚举一个a,然后验证(代码注释有)。

这样求出a,b之后,这个题就解完了,直接按递推公式把所有项求出即可。

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<sstream>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<cmath>
#define up(i, x, y) for(int i = x; i <= y; i++)
#define down(i, x, y) for(int i = x; i >= y; i--)
#define MAXN ((int)1e3 + 10)
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
ll arr[MAXN];
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 -= (a / b) * x;
    }
}
int main()
{
    ll a, b, y, d;
    ll n; scanf("%lld", &n);
    for(ll i = 1; i < 2 * n; i += 2)
    {
        scanf("%d", &arr[i]);
    }
    up(j, 0, 10000)
    {
        a = j;   //枚举a
        ll c = arr[3] - a * a * arr[1]; //相当于ax+by=c中的c
        exgcd(a + 1, 10001, d, b, y);  //带入exgcd(),求解b
        if(c % d) continue;//如果t不可以整出d,那么这个a不行,因为只有gcd(a, b) | c 才有整解
        ll flag = 1;
        b = b * (c / d); //按倍数(整体扩大t/d倍)关系求出b
        for(int i = 2; i <= 2 * n; i++)
        {
            if(i&1){ //奇数的时候再次验证 a,b 是否对
                if(arr[i] != (a * arr[i - 1] + b) % 10001 ){ //如果不满足
                    flag = 0;
                    break;
                }
            }
            else{
                arr[i] = (a * arr[i - 1] + b) % 10001;
            }
        }
        if(!flag) continue;
        else{
            for(int i = 2; i <= 2 * n; i += 2)
            {
                cout<<arr[i]<<'\n';
            }
            break;
        }
    }

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值