hdu_4869_ 費馬小引理+快速冪

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

Turn the pokers

  題意:

    給定m張牌,初始狀態均為反面朝上。給定n次操作,每次指定所要翻的牌數,求n次操作後的牌的狀態總數 mod 1000000009。

  輸入:

    第一行n和m,代表n次操作和m張牌;

    第二行n個數,代表每次要翻的牌的張數。

  輸出:

    方案數 mod 1000000009。

 

  思路:

    設反面為0,正面為1。對於一張牌翻兩次和兩張牌翻一次 得到的奇偶性相同,所以結果中最少的1(S)和最多的1(E)的奇偶性相同。如果找到了S和E,那麼,介於這兩個數之間且與這兩個數奇偶性相同的數均可取到,然後在這個區間內組合數求解即可。

    因此這道題要解決好兩個問題,一是求邊界條件S和E,另一個是求在這之間內組合數求解。

    注意到這道題資料很大,C(n, m) = n!/(m!*(n-m)!),除法運算變得不合適。由 費馬小定理 a^(p-1) = 1%p,那麼,a^(p-2) = 1/a%p,利用這個公式,得到1/(m!*(n-m)!) = (m!*(n-m)!)^(p-2) mod p,即C(n, m) = n!*(m!*(n-m)!)^(p-2) mod p,這樣就可以變除為乘。(也可以用求逆元 ing…)

    求(n-m)!)^p-2 mod p中用快速冪簡化運算。

 

    代碼:

  

 1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 #define X 100005 6 using namespace std; 7  8 long long f[X]; 9 long long mod = 1000000009;10 11 void initial()12 {13     f[0] = 1;14     for(int i = 1; i < X; i++)15         f[i] = (f[i-1]*i)%mod;16 }17 18 // 快速冪19 long long PowerMod(long long a, long long b)20 {21     long long ans = 1;22     a = a % mod;23     while(b>0) {24         if(b % 2 == 1)25         ans = (ans * a) % mod;26         b = b/2;27         a = (a * a) % mod;28     }29     return ans;30 }31 32 int main()33 {34     int n, m, x;35     int s, e, S, E;36 37     initial(); // 求出n的階乘38 39     while(scanf("%d%d", &n, &m) != EOF)40     {41         s = 0; e = 0;42         for(int i = 0; i < n; i++) {  // 找出最多和最少的1的個數43             scanf("%d", &x);44             if(x <= s) S = s - x;45             else if(e >= x) S = (s%2 == x%2)?0:1;46                 else S = x - e;47             if(e+x <= m) E = e + x;48             else if(s+x <= m) E = (((s+x)%2) == (m%2)?m:m-1);49                 else E = 2*m-(s+x);50             s = S;51             e = E;52         }53         long long ans = 0;54         for(int i = S; i <= E; i+=2) // 使用快速冪和費馬小定理得出結果55             ans += ((f[m]%mod)*(PowerMod((f[i]*f[m-i])%mod, mod-2)%mod))%mod;56         printf("%lld\n", ans%mod);57     }58     return 0;59 }
View Code

 

    Ps:看了別人的代碼,感覺都和別人的一樣了,不熟練這樣還可以理解,以後就再這樣不行了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.