zoukankan      html  css  js  c++  java
  • poj2115——拓展欧几里德求模线性同余方程的最小正整数解

    poj2115——拓展欧几里德求模线性同余方程的最小正整数解

    C Looooops
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 18926   Accepted: 4973

    Description

    A Compiler Mystery: We are given a C-language style for loop of type 
    for (variable = A; variable != B; variable += C)
    
    statement;

    I.e., a loop which starts by setting variable to value A and while variable is not equal to B, repeats statement followed by increasing the variable by C. We want to know how many times does the statement get executed for particular values of A, B and C, assuming that all arithmetics is calculated in a k-bit unsigned integer type (with values 0 <= x < 2k) modulo 2k

    Input

    The input consists of several instances. Each instance is described by a single line with four integers A, B, C, k separated by a single space. The integer k (1 <= k <= 32) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, C < 2k) are the parameters of the loop. 

    The input is finished by a line containing four zeros. 

    Output

    The output consists of several lines corresponding to the instances on the input. The i-th line contains either the number of executions of the statement in the i-th instance (a single integer number) or the word FOREVER if the loop does not terminate. 

    Sample Input

    3 3 2 16
    3 7 2 16
    7 3 2 16
    3 4 2 16
    0 0 0 0
    

    Sample Output

    0
    2
    32766
    FOREVER
    题意:for(x=A;x!=B;x+=C,x%=1LL<<k) 求解结束时循环的次数
    思路:显然是求解方程(A+Cx)%n=B,(n=1<<k),变形得Cx%n=(B-A)%n,即转为模线性同余方程 Cx=(B-A)(mod n),扩展gcd解之即可
    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    
    using namespace std;
    
    const int maxn=1000100;
    const int INF=(1<<28);
    typedef long long ll;
    
    ll A,B,C,k;
    ll x,y;
    
    ll exgcd(ll a,ll b, ll &x, ll &y)
    {
        if(b==0){
            x=1;y=0;
            return a;
        }
        ll r=exgcd(b,a%b,x,y);
        ll t=y;
        y=x-a/b*y;
        x=t;
        return r;
    }
    
    bool mod_linear_equation(ll a,ll b,ll n)
    {
        ll d=exgcd(a,n,x,y);
        if(b%d) return false;
        x=x*(b/d)%n;
        x=(x%(n/d)+n/d)%(n/d);
        return true;
    }
    
    int main()
    {
        while(cin>>A>>B>>C>>k,A||B||C||k){
            if(mod_linear_equation(C,B-A,1LL<<k)) cout<<x<<endl;
            else cout<<"FOREVER"<<endl;
        }
        return 0;
    }
    View Code


    没有AC不了的题,只有不努力的ACMER!
  • 相关阅读:
    TextView 内容设置成上下滑动 和 代码设置字体颜色
    Android提供了4种在其他线程中访问UI线程的方法
    Android 左右滑屏效果
    【自定义控件】 GridView
    【动画】【特效】activity跳转华丽的过渡效果(转载)
    Android获取设备型号、SDK版本及其系统版本
    【JSON】数据解析
    Android中文API集合
    【AssetManager】的使用与资源预加载
    @property(nonatomic,retain)
  • 原文地址:https://www.cnblogs.com/--560/p/4372794.html
Copyright © 2011-2022 走看看