Submission #876959

# Submission time Handle Problem Language Result Execution time Memory
876959 2023-11-22T15:00:44 Z boris_mihov Beautiful row (IZhO12_beauty) C++17
100 / 100
2258 ms 194348 KB
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cassert>
#include <vector>

typedef long long llong;
const int MAXN = 21;
const int MAXB = (1 << 20);

int n;
int a[MAXN];
int binary[MAXN];
int ternary[MAXN];
llong dp[MAXB][MAXN];
bool bl[MAXB][MAXN];

llong f(int mask, int last)
{
    if (__builtin_popcount(mask) == n)
    {
        return 1;
    }

    if (bl[mask][last])
    {
        return dp[mask][last];
    }

    bl[mask][last] = true;
    for (int next = 1 ; next <= n ; ++next)
    {
        if (mask & (1 << next - 1))
        {
            continue;
        }

        if (last == 0 || binary[last] == binary[next] || ternary[last] == ternary[next])
        {
            dp[mask][last] += f(mask | (1 << next - 1), next);
        }
    }

    return dp[mask][last];
}

void solve()
{
    for (int i = 1 ; i <= n ; ++i)
    {
        binary[i] = __builtin_popcount(a[i]);
        int curr = a[i];

        while (curr > 0)
        {
            ternary[i] += (curr % 3) == 1;
            curr /= 3;
        }
    }

    std::cout << f(0, 0) << '\n';
}

void input()
{
    std::cin >> n;
    for (int i = 1 ; i <= n ; ++i)
    {
        std::cin >> a[i];
    }
}

void fastIOI()
{
    std::ios_base :: sync_with_stdio(0);
    std::cout.tie(nullptr);
    std::cin.tie(nullptr);
}

int main()
{
    fastIOI();
    input();
    solve();

    return 0;
}

Compilation message

beauty.cpp: In function 'llong f(int, int)':
beauty.cpp:33:31: warning: suggest parentheses around '-' inside '<<' [-Wparentheses]
   33 |         if (mask & (1 << next - 1))
      |                          ~~~~~^~~
beauty.cpp:40:51: warning: suggest parentheses around '-' inside '<<' [-Wparentheses]
   40 |             dp[mask][last] += f(mask | (1 << next - 1), next);
      |                                              ~~~~~^~~
# Verdict Execution time Memory Grader output
1 Correct 1 ms 2396 KB Output is correct
2 Correct 0 ms 348 KB Output is correct
3 Correct 0 ms 348 KB Output is correct
4 Correct 0 ms 2396 KB Output is correct
5 Correct 1 ms 348 KB Output is correct
6 Correct 1 ms 632 KB Output is correct
7 Correct 0 ms 604 KB Output is correct
8 Correct 1 ms 2396 KB Output is correct
9 Correct 1 ms 604 KB Output is correct
10 Correct 1 ms 2396 KB Output is correct
11 Correct 10 ms 4700 KB Output is correct
12 Correct 8 ms 4188 KB Output is correct
13 Correct 52 ms 13404 KB Output is correct
14 Correct 336 ms 49760 KB Output is correct
15 Correct 376 ms 50968 KB Output is correct
16 Correct 255 ms 51024 KB Output is correct
17 Correct 329 ms 50968 KB Output is correct
18 Correct 204 ms 49764 KB Output is correct
19 Correct 2177 ms 194320 KB Output is correct
20 Correct 2258 ms 194348 KB Output is correct