题解:P10723 [GESP202406 七级] 黑白翻转

· · 题解

题目大意

给你 n 个点的初始权值 a_i ,以及 n 个点构成的树,要求删去权值为 0 的点后,该图仍是一棵树,问至少需要把多少个权值为 1 的点的权值更改成 0。

思路

显然,如果一个权值为 1 的点到达根的路径上有权值为 0 的点,那么这些权值为 1 的点需要更改。

于是我们只需要 dfs 一下,一个点想对答案有贡献当且仅当其子树中有权值为 1 的点且改点权值为 0。

小细节:如果你按照上面的代码去码的话,会被这组样例卡掉:

5
1 0 0  0 0
1 2
2 3
2 4
2 5

画图后发现,原因是根是白点它的其中一个儿子是黑点,其它的全是白点,那么很显然是不需要做改变的,但由于黑点的存在,致使根对答案贡献了 1,于是想到钦定黑点作为根即可避免此类情况。

代码:

#include<bits/stdc++.h>
using namespace std;

const int zyc = 100000+10 ;

int n,a[zyc],ans,root;
vector<int>son[zyc]; 

char *p1,*p2,buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read()
{
    int x=0,f=1;
    char ch=nc();
    while(ch<48||ch>57)
    {
        if(ch=='-')
            f=-1;
        ch=nc();
    }
    while(ch>=48&&ch<=57)
        x=x*10+ch-48,ch=nc();
    return x*f;
}

inline bool Dfs(int u,int fa){
    bool flag=0,ff=0;ff|=a[u]; 
    for(int i=0,v;i<son[u].size();i++){
        v=son[u][i];
        if(v==fa)  continue;
        bool f=Dfs(v,u);ff|=f;
        if(a[u]==0&&f&&(!flag))
            ans++,flag=1;
    }
    return ff ; 
}

signed main(){
    n=read();
    for(int i=1;i<=n;i++) {
        a[i]=read();
        if(a[i])  root=i;
    }
    for(int i=1,u,v;i<n;i++){
        u=read();v=read();
        son[u].push_back(v);
        son[v].push_back(u);
    }
    Dfs(root,0);
    return 0*printf("%d\n",ans);
}

另:以下两组样例是本人手玩出来的,读者可以自行检验自己的代码。

Input:
5
0 1 0  1 0
1 2 
2 3
3 4
4 5

Output:
1
Input:
5
1 0 0  0 0
1 2
2 3
2 4
2 5

Output:
0