Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

The answer by Tuxdude is perfect:

http://stackoverflow.com/questions/11161465/existence-of-a-permutation-under-constraints-interview-street-manipulative-nu

Lesson learnt: always try to dig more insightful thoughts to find hidden\subtle mechanisms.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;


int main() 
{
    //    Get input
    int n; cin >> n;
    vector<int> in(n, 0);
    for(int i = 0; i < n; i ++)
        cin >> in[i];

    //
    int maxbit = floor(log(*std::max_element(in.begin(), in.end()))/log(2));
    int k = -1;
    for (int bitcnt = maxbit - 1; bitcnt >= 0; bitcnt --)
    {
        bool bValid = true;
        unordered_map<int, unsigned> rec;
        for(auto v : in)
        {
            int vs = v >> bitcnt;
            rec[vs] ++;
            if(rec[vs] > (n/2))
            {
                bValid = false;
                break;
            }
        }
        if(!bValid)
        {
            continue;
        }
        k = bitcnt;
        break;
    }
    cout << k << endl;
    return 0;
}

 

posted on 2015-06-10 02:26  Tonix  阅读(278)  评论(0编辑  收藏  举报