2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest D:Distribution in Metagonia(構造)

來源:互聯網
上載者:User

標籤:

http://codeforces.com/gym/100801/attachments

 

題意:給出一個數n(1 <= n <= 1e18),將 n 拆成 m 個整數,其中 m 必須是 2^x * 3^y 的形式,並且 x 和 y 不能被彼此整除, 輸出 m 並將這些整數輸出。

思路:Inspired by http://blog.csdn.net/snowy_smile/article/details/49852091 。

 

第一步:因為要求的 m 是 2^x * 3^y 的形式,所以如果 n 可以直接被 2^x * 3^y 整除的話,即 n % (2^x * 3^y) == 0,那麼就可以直接輸出 n 了。如果不能被直接整除的話,我們可以先將 n 拆解成不能被 3 和 2 整除的形式,這裡的話用一個 mul 記錄 n 除以多少。

 1     while(n % 3 == 0) { 2         n /= 3; 3         mul *= 3; 4     } 5     while(n % 2 == 0) { 6         n /= 2; 7         mul *= 2; 8     } 9     if(n == 1) {10         num[m++] = mul;11         return ;12     }

 

第二步:那麼更重要的問題是如果 n 不能被 2 或 3 整除,同時也不為 1 時應該怎麼做。因為不能被 2 整除,所以這時的 n 必定是一個奇數。那麼我們可以將 n 減去 w,w = 3^y && w < n,我們所做的是將 n 拆解出一個 w(w必定為奇數),那麼剩下的 n 就是一個偶數了,這個時候我們又能回到第一步進行遞迴求解了。因為我們拆出的 w  也是組成 n 的一部分,因此要記錄下來,記錄的數值是 w * mul,因為我們前面 n 除以了 一些 2 和 3 ,我們用 mul 記錄下來了,因此這個時候要乘回去,所以是 w * mul。

1 else {2         long long x = 3;3         while(x * 3 < n) {4             x *= 3;5         }6         n -= x;7         num[m++] = x * mul;8         solve(n, mul);9     }

 

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 #include <queue> 7 #include <map> 8 #include <cstdlib> 9 using namespace std;10 typedef long long LL;11 LL num[150];12 int m;13 /*14 題意:將n拆成m個數,這m個數的表示是15 */16 void solve(LL n, LL mul)17 {18     while(n % 3 == 0) {19         n /= 3;20         mul *= 3;21     }22     while(n % 2 == 0) {23         n /= 2;24         mul *= 2;25     }26     if(n == 1) {27         num[m++] = mul;28         return ;29     } else {30         long long x = 3;31         while(x * 3 < n) {32             x *= 3;33         }34         n -= x;35         num[m++] = x * mul;36         solve(n, mul);37     }38 }39 40 int main()41 {42     freopen("distribution.in", "r", stdin);43     freopen("distribution.out", "w", stdout);44     int t;45     cin >> t;46     while(t--) {47         LL n;48         cin >> n;49         m = 0;50         solve(n, 1);51         cout << m << endl;52         for(int i = 0; i < m; i++) {53             cout << num[i];54             if(i != m-1) cout << " ";55             else cout << endl;56         }57     }58     return 0;59 }

 

 

2015-2016 ACM-ICPC, NEERC, Northern Subregional Contest D:Distribution in Metagonia(構造)

聯繫我們

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