HackerRank - "Candles Counting" - DIFFICULT

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

转载于:https://www.cnblogs.com/tonix/p/4717711.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值