CodeForces - 338D GCD Table 同余方程组

该博客介绍了如何解决CodeForces上的338D问题,即根据GCD表格和给定数组判断数组是否与表格某一行的连续部分匹配。通过分析,博主提出最小可能的匹配行是数组元素的最小公倍数,并形成同余方程组来找到起始列。最后,博主提供了求解此问题的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:给你一张N*M的表,表中(i,j)的值为gcd(i,j),再给你一个长度为K的数组a[i],问这个数组是否与表中某一行的一段完全重合

思路:最小可能出现的行一定是LCM(a[0],a[1],...,a[K]),然后假设为第x列为开始位置

x=0%a[0]

x+1=0%a[1]

...

x+K-1=0%a[K-1]

发现没,这就是同余方程组,然后求出最小的非负整数解,然后把这个解代入,看gcd是不是和数组a完全重合

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
// 0x3f3f3f3f

const int maxn=1e4+50;
LL r[maxn],a[maxn];
void exgcd(LL a,LL b,LL &d,LL &x,LL &y){
    if(b==0){
        d=a;x=1;y=0;
    }
    else{
        exgcd(b,a%b,d,y,x);
        y-=(a/b)*x;
    }
}
LL solve(int n){//求x≡ri(mod ai)
    LL nr=r[0],na=a[0],d,x,y;
    bool flag=true;
    for(int i=1;i<n;i++){
        exgcd(na,a[i],d,x,y);
        LL c=r[i]-nr;
        if(c%d!=0)
            flag=false;
        LL t=a[i]/d;
        x=(x*(c/d)%t+t)%t;
        nr=na*x+nr;
        na=na*(a[i]/d);
    }
    if(!flag)//无解
        return -1;
    return nr;
}
LL N,M;
int K;
bool judge(){
    LL LCM=1;
    for(int i=0;i<K;i++)
        LCM=LCM/gcd(LCM,a[i])*a[i];
    if(LCM>N) return false;
    for(int i=0;i<K;i++) r[i]=-i;
    LL J=solve(K);
    if(J==0) J=LCM;
    if(J>M-K+1||J<=0) return false;
    for(int i=0;i<K;i++)
        if(gcd(LCM,J+i)!=a[i])
            return false;
    return true;
}
int main(){


    while(~scanf("%lld%lld%d",&N,&M,&K)){
        for(int i=0;i<K;i++)
            scanf("%lld",&a[i]);
        if(judge()) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值