zoukankan      html  css  js  c++  java
  • HackerRank

    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
    ", res);
        return 0;
    }
    View Code
  • 相关阅读:
    [LuoGu] P1004 方格取数
    [LuoGu] P1018 乘积最大
    [LuoGu] P2758 编辑距离
    [JZOJ] 01知多少
    [LuoGu] P1731 生日蛋糕
    $mathcal{Const,Inline,Register}$用法总结
    T2027 蜈蚣
    T57274 黑暗城堡
    P2312 解方程
    AT2412 最大の和
  • 原文地址:https://www.cnblogs.com/tonix/p/4717711.html
Copyright © 2011-2022 走看看