POJ 2115 C Looooops

來源:互聯網
上載者:User

標籤:poj   擴充歐幾裡德演算法   

題目:http://poj.org/problem?id=2115

題意:對於C的for(i=A ; i!=B ;i +=C)迴圈語句,問在k位儲存系統中迴圈幾次才會結束。若在有限次內結束,則輸出迴圈次數。否則輸出死迴圈。

思路:這道題是一個擴充歐幾裡德演算法的拓展,求單變元模線性方程 即:Cx=(B-A)(mod 2^k) 

擴充歐幾裡得演算法和單變元模線性方程(傳送門) + 比較詳細的部落格

代碼:

/*ID: [email protected]PROG:LANG: C++*/#include<map>#include<set>#include<queue>#include<stack>#include<cmath>#include<cstdio>#include<vector>#include<string>#include<fstream>#include<cstring>#include<ctype.h>#include<iostream>#include<algorithm>#define INF (1<<30)#define PI acos(-1.0)#define mem(a, b) memset(a, b, sizeof(a))#define rep(i, n) for (int i = 0; i < n; i++)#define debug puts("===============")#define eps (1e-6)typedef long long ll;using namespace std;ll extend_gcd(ll a, ll b, ll &x, ll &y) {    if (b == 0) {        x = 1, y = 0;        return a;    }    else {        ll r = extend_gcd(b, a % b, y, x);        y -= x * (a / b);        return r;    }}vector<ll> line_mod_equation(ll a, ll b, ll n) {    ll x, y;    ll d = extend_gcd(a, n, x, y);    vector<ll> ans;    ans.clear();    if (b % d == 0) {        x = (x % n + n) % n;        x %= (n / d);        ans.push_back(x * (b / d) % (n / d));        //for (ll i = 1; i < d; i++) ans.push_back((ans[0] + i * n / d) % n);    }    return ans;}int main () {    //freopen("2.txt", "w", stdout);    ll a, b, c, k;    while(scanf("%lld%lld%lld%lld", &a, &b, &c, &k) , a || b || c || k) {        ll n = 1LL << k;        ll p = ((b - a) % n + n) % n;        vector<ll> ans = line_mod_equation(c, p, n);        if (ans.size() == 0) puts("FOREVER");        else printf("%lld\n", ans[0]);    }    return 0;}


POJ 2115 C Looooops

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.