zoukankan      html  css  js  c++  java
  • C Looooops(扩展欧几里得)题解

    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 < 2 k) modulo 2 k

    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 < 2 k) 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


    思路:

    和之前做的差不多:青蛙

    发现模线性方程不会转化orz,贴一下:模线性方程

    模线性方程转化:当 a*xb mod m时,可以转化为 a*x+m*y=b求解x,y 

    那么我们先来列出原题模线性方程:C*t+A B mod(2^k)  ==>   C*t ≡ B-A  mod(2^k) ==>  C*t + (2^k)*y B-

    代码:

    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<queue>
    #include<cmath>
    #include<string>
    #include<map>
    #include<stack> 
    #include<set>
    #include<vector>
    #include<iostream>
    #include<algorithm>
    #define INF 0x3f3f3f3f
    #define ll long long
    const int N=2000000000;
    const int MAX=2100000000;
    const int MOD=1000; 
    using namespace std;
    ll ex_gcd(ll a,ll b,ll &x,ll &y){
    	ll d,t;
    	if(b==0){
    		x=1;
    		y=0;
    		return a;
    	}
    	d=ex_gcd(b,a%b,x,y);
    	t=x-a/b*y;
    	x=y;
    	y=t;
    	return d;
    }
    int main(){
    	ll a,b,c,k,A,B,C,d,x,y;
    	while(~scanf("%lld%lld%lld%lld",&A,&B,&C,&k) && A+B+C+k){
    		a=C;
    		b=(ll)1<<k;
    		c=B-A;
    		d=ex_gcd(a,b,x,y);
    		if(c%d!=0){
    			printf("FOREVER
    ");
    		}
    		else{
    			x=x*c/d;
    			ll k=b/d;
    			x=(x%k+k)%k;
    			printf("%lld
    ",x);
    		}
    	} 
    	return 0;
    }

  • 相关阅读:
    bzoj 1176 cdq分治套树状数组
    Codeforces 669E cdq分治
    Codeforces 1101D 点分治
    Codeforces 1100E 拓扑排序
    Codeforces 1188D Make Equal DP
    Codeforces 1188A 构造
    Codeforces 1188B 式子转化
    Codeforces 1188C DP 鸽巢原理
    Codeforces 1179D 树形DP 斜率优化
    git commit -m "XX"报错 pre -commit hook failed (add --no-verify to bypass)问题
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9409112.html
Copyright © 2011-2022 走看看