码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - "Candles Counting" - DIFFICULT

时间:2015-08-10 13:34:14      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

It should be categorized as ‘Advanced‘ I think ... Anyway, Fenwick tree is the key.

Editorial: https://www.hackerrank.com/challenges/candles-2/editorial. Editorial provided a very smart, Inclusion-Exclusion Principle based algorithm. However Editorial solution didn‘t pass all test cases though - there‘s coding issue in its Fenwick part. Here is a working one by using TopCoder Tutorial‘s Fenwick code:

技术分享
#include <cstdio>
#include <cstring>
const int MAX_N = 50000;
const int MAX_K = 7;
const int MAX_H = 50000;

// modulo code
const int mod = 1000000007;
void madd(int& a, int b){ a += b;  if (a >= mod) a -= mod; }

//////////////////
// Fenwick Tree //
int ft[MAX_N + 10];
void update(int i, int x)
{
    for (; i <= MAX_N; i += (i & -i))
        madd(ft[i], x);
}

int query(int i)
{ 
    int s = 0;  
    for (; i > 0; i -= (i & -i)) 
        madd(s, ft[i]);  
    return s; 
}
//////////////////

unsigned countBits(int x)
{
    unsigned cnt = 0;
    while (x)
    {
        cnt++;
        x &= x - 1;
    }
    return cnt;
}

int main()
{
    int N, K;
    int H[MAX_N + 1], C[MAX_N + 1];
    
    scanf("%d%d", &N, &K);
    for (int i = 0; i < N; i++)
    {
        scanf("%d%d", H + i, C + i);
    }

    int res = 0;
    for (int mask = 0; mask < (1 << K); mask++)
    {
        memset(ft, 0, sizeof(ft));

        //    Count number of sub-sequences of given ‘mask‘
        int tmp = 0;
        for (int i = 0; i < N; i++)
        {
            if ((mask >> (C[i] - 1)) & 1)
            {
                int cnt = 1 + query(H[i] - 1);                
                update(H[i], cnt);

                madd(tmp, cnt);
            }
        }

        //    Inclusion-Exclusion Principle
        if (countBits(mask) % 2 == K % 2)
        {
            madd(res, tmp);
        }
        else
        {
            madd(res, mod - tmp);
        }
    }
    printf("%d\n", res);
    return 0;
}
View Code

HackerRank - "Candles Counting" - DIFFICULT

标签:

原文地址:http://www.cnblogs.com/tonix/p/4717711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!