QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#601713#7736. Red Black TreewxgmjfhyML 0ms3868kbC++201.7kb2024-09-30 11:30:182024-09-30 11:30:19

Judging History

你现在查看的是最新测评结果

  • [2024-09-30 11:30:19]
  • 评测
  • 测评结果:ML
  • 用时:0ms
  • 内存:3868kb
  • [2024-09-30 11:30:18]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;
// #pragma GCC optimize(3)

// std::mt19937_64 rng {std::chrono::steady_clock::now().time_since_epoch().count()};

int n;
string s;

inline void solve(){
    cin>>n;

    cin>>s;
    s=" "+s;    

    vector<vector<int> >g(n+1);
    for(int i=2,p;i<=n;i++){
        cin>>p;
        g[p].push_back(i);
    }

    vector<int>dep(n+1),mn(n+1,1e9);
    auto pre=[&](auto self,int u,int fa)->void {
        dep[u]=dep[fa]+1;
        if(g[u].empty()){
            mn[u]=dep[u];
            return;
        }
        for(auto t:g[u]){
            self(self,t,u);
            mn[u]=min(mn[u],mn[t]);
        }
    };
    pre(pre,1,0);

    vector<int>ans(n+1,1e9);
    vector<vector<int> >dp(n+1);
    auto dfs=[&](auto self,int u)->void {
        if(g[u].empty()){
            dp[u].assign(2,0);
            dp[u][0]=(s[u]=='1');
            dp[u][1]=(s[u]=='0');
            ans[u]=0;
            return;
        }
        dp[u].assign(mn[u]-dep[u]+1+1,0);
        for(auto t:g[u]){
            self(self,t);
            for(int i=0;i<=mn[u]-dep[u]+1;i++){
                if(i==0)dp[u][i]+=dp[t][i]+(s[u]=='1');
                else if(i==mn[u]-dep[u]+1)dp[u][i]+=dp[t][i-1]+(s[u]=='0');
                else dp[u][i]+=min(dp[t][i]+(s[u]=='1'),dp[t][i-1]+(s[u]=='0'));
            }
        }
        for(int i=0;i<=mn[u]-dep[u]+1;i++)ans[u]=min(ans[u],dp[u][i]);
        
    };
    dfs(dfs,1);

    for(int i=1;i<=n;i++)cout<<ans[i]<<" \n"[i==n];
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    // cout<<setiosflags(ios::fixed)<<setprecision(10);

    int _=1;
    cin>>_;
    while(_--){
        solve();
    }
    return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 0ms
memory: 3868kb

input:

2
9
101011110
1 1 3 3 3 6 2 2
4
1011
1 1 3

output:

4 1 2 0 0 0 0 0 0
2 0 0 0

result:

ok 2 lines

Test #2:

score: -100
Memory Limit Exceeded

input:

6107
12
000000001000
1 2 3 2 5 4 4 7 3 8 11
19
1100111101111011110
1 2 1 1 4 5 2 4 3 2 2 7 10 2 11 3 15 5
7
0111110
1 1 2 2 1 5
3
000
1 1
7
1000011
1 2 3 3 5 4
7
0001001
1 1 1 3 5 3
8
00111000
1 1 3 2 5 2 7
11
11111110111
1 1 1 4 5 4 5 2 5 1
15
110101101000010
1 2 3 2 1 5 2 5 6 5 8 7 9 14
10
0101000...

output:

1 1 1 1 0 0 0 0 0 0 0 0
6 2 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0
0 0 0
0 0 0 0 0 0 0
2 0 1 0 0 0 0
2 1 0 0 0 0 0 0
5 0 0 2 1 0 0 0 0 0 0
4 3 0 0 2 0 0 0 0 0 0 0 0 0 0
2 0 1 0 0 0 0 0 0 0
6 5 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0
1 1 0 0 0
7 1 0 1 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 0 0
6 4 ...

result: