제출 #1328902

#제출 시각아이디문제언어결과실행 시간메모리
1328902paronmanukyanUzastopni (COCI15_uzastopni)C++20
160 / 160
85 ms32712 KiB
#include <bits/stdc++.h>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;

#define all(x) x.begin(), x.end()
#define pb push_back
#define FASTIO ios_base::sync_with_stdio(false); cin.tie(nullptr);
#define sz(x) int(x.size())
#define rep(a,b,c,d) for(int a=b;a<=c;a+=d)

const int N = 1e4 + 1;
const int M = 101;

vector<int> adj[N];
int v[N];

struct BS {
    uint64_t a[2];
    void reset() { a[0] = a[1] = 0; }
    void set(int pos) {
        if(pos < 64) a[0] |= (1ULL << pos);
        else a[1] |= (1ULL << (pos - 64));
    }
    bool test(int pos) const {
        if(pos < 64) return a[0] & (1ULL << pos);
        return a[1] & (1ULL << (pos - 64));
    }
    void OR(const BS &b) {
        a[0] |= b.a[0];
        a[1] |= b.a[1];
    }
    int count() const {
        return __builtin_popcountll(a[0]) +
               __builtin_popcountll(a[1]);
    }
};

BS dp[N][M];

void dfs(int node) {

    rep(i,0,M-1,1) dp[node][i].reset();

    dp[node][v[node]].set(v[node]);

    if(!sz(adj[node]))
        return;

    BS chld[M];
    rep(i,0,M-1,1) chld[i].reset();

    for(auto to: adj[node]) {
        dfs(to);
        rep(i,1,M-1,1)
            chld[i].OR(dp[to][i]);
    }

    for(int i = M-1; i >= 1; i--) {
        for(int j = i+1; j < M; j++) {
            if(chld[i].test(j-1))
                chld[i].OR(chld[j]);
        }
    }

    rep(i,1,v[node],1) {
        rep(j,v[node],M-1,1) {
            if((i==v[node] || chld[i].test(v[node]-1)) &&
               (j==v[node] || chld[v[node]+1].test(j)))
                dp[node][i].set(j);
        }
    }
}

int main() {
    FASTIO

    int n;
    cin >> n;

    rep(i,1,n,1)
        cin >> v[i];

    rep(i,1,n-1,1) {
        int a,b;
        cin >> a >> b;
        adj[a].pb(b);
    }

    dfs(1);

    long long ans = 0;
    rep(i,1,M-1,1)
        ans += dp[1][i].count();

    cout << ans << "\n";
}
#Verdict Execution timeMemoryGrader output
Fetching results...