cf1118f1

Meaning of the questions:

Given a tree, the tree has a point in the three cases 1, 2, 0 represents the point colorless. You now need to cut off some of these tree edges cut off so that each edge is divided into two portions each comprising at most one color point, i.e. the two parts of the divided points can not be 1,2-point inclusions (may be 0 any), up to ask you a few have such a cut point.

dfs solved all points to itself as the root of the subtree i 1 and 2, the number of nodes num1, num2, then num1 according subtree between the mother tree, calculating the difference value num2, can be another part of the i 1 2, the number of nodes, and then determine whether the condition to two portions.

 

#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;

const int N = 20010,M = 1001010;
int head[N],ver[M],Next[M],tot;
int a[N],n;
int num1[N],num2[N];

void add(int x,int y)
{
    ver[++ tot] = y; Next[tot] = head[x]; head[x] = tot;
}

void dfs(int x,int far)
{
    if(a[x] == 1) num1[x] = 1;
    else if(a[x] == 2)num2[x] = 1;
    for(int i = head[x]; i; i = Next[i]){
        int y = ver[i];
        if(y == far) continue;
        dfs(y,x);
        num1 [x] + = num1 [and];
        num2 [x] + = num2 [y];
    }
}
int main ()
{
    scanf("%d",&n);
    for(int i = 1; i <= n; i ++) scanf("%d",&a[i]);
    for(int i = 1; i < n; i ++){
        int x,y; scanf("%d%d",&x,&y);
        add(x,y); add(y,x);
    }
    dfs(1,-1);
    int years = 0;
    for(int i = 2; i <= n; i ++){
        int x = num1[1] - num1[i];
        int y = num2[1] - num2[i];
        if(num1[i] && num2[i]) continue;
        else if(x == 0 || y == 0) ans ++;
    }
     printf("%d\n",ans);
}

 

Guess you like

Origin www.cnblogs.com/yrz001030/p/12406150.html