您的位置:首页 > 其它

poj 1702 平衡三进制

2015-07-24 21:41 239 查看
思路:

平衡三进制。

先将n转换为3进制,再转化为平衡3进制,-1项全部移到右面,左右面分别输出。

平衡三进制具体转化方法

先转化为用0,1,2表示的3进制,然后通过“借位”转换

若对应的系数为2,则变为-1,下一位+1

若对应的系数为3,则变为0,下一位+1

为0或1时不变

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstring>
#include <limits.h>

#define Long long long
#define uint unsigned int
#define N
#define mod 1000000007
#define inf 100000000
#define eps 1e-10
#define For(i,l,r) for(int i=l;i<=r;i++)
#define Dor(i,r,l) for(int i=r;i>=l;i--)

using namespace std;

ifstream in("/Users/urey/data/input.txt");
//_________________________________________________________________________________

//eg: 20 (10进制)-> 202 (3进制)-> 1,-1,1,-1 (平衡3进制)

int main(int argc, const char * argv[]) {
    int n, weight;
    int poses[20];
    int j = 1;//3^0
    for(int i = 0; i < 20; ++i) {
        poses[i] = j;
        j *= 3;
    }

    int tribit[21];
    cin>>n;
    for(int i = 0; i < n; ++i) {
        cin>>weight;

        //转换为三进制
        memset(tribit, 0, sizeof(tribit));
        for(int j = 19; j >= 0; --j) {
            tribit[j] = weight/poses[j];
            weight %= poses[j];
        }
//        cout<<"3进制"<<endl;
//        for(int j = 20; j >= 0; --j) {
//            cout<<tribit[j];
//        }
        int count = 0;
        //转化为平衡三进制
        for(int j = 0; j <= 19; ++j) {
            if(tribit[j] == 2) {
                tribit[j] = -1;
                ++count;
                tribit[j+1] += 1;
            }else if(tribit[j] == 3) {
                tribit[j] = 0;
                tribit[j+1] += 1;
            }
        }
//        cout<<endl;
//        cout<<"平衡3进制"<<endl;
//        for(int j = 20; j >= 0; --j) {
//            cout<<tribit[j];
//        }
//        cout<<endl;
        //输出左半部分
        if(count) {
            int j = 0;
            while(tribit[j] != -1) {
                ++j;
            }
            cout<<poses[j];
            for(++j; j < 21; ++j) {
                if(tribit[j] == -1) {
                    cout<<","<<poses[j];
                }
            }
        }else {
            cout<<"empty";
        }
        cout<<" ";
        //输出右半部分
        int j = 0;
        while(tribit[j] != 1) {
            ++j;
        }
        cout<<poses[j];
        for(++j; j < 21; ++j) {
            if(tribit[j] == 1) {
                cout<<","<<poses[j];
            }
        }
        cout<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: