BZOJ 1907: Path Tree cover

dfs up when greedy. Greedy correctness Skip (Apparently it should ..)

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
const int N = 1e4+10;
inline int read()
{
    register int x = 0 , f = 0; register char c = getchar();
    while(c < '0' || c > '9') f |= c == '-' , c = getchar();
    while(c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0' , c = getchar();
    return f ? -x : x;
}
int n , cnt;
int head[N] , vis[N] , f[N];
struct edge{ int v , nex; } e[N<<1];
inline void add(int u , int v) { e[++cnt].v = v; e[cnt].nex = head[u]; head[u] = cnt; return ; }

void dfs(int x , int fa)
{
    f[x] = 1; int tot = 0;
    for(int i = head[x] , v ; i ; i = e[i].nex)
    {
        v = e[i].v; if(v == fa) continue;
        dfs(v , x); f[x] += f[v]; if(!vis[v]) tot++;
    }
    if(tot >= 2) f[x] -= 2 , vis[x] = 1;
    else if(tot == 1) f[x] -= 1;
    return ;
}

void solve()
{
    n = read(); cnt = 0;
    for(int i = 1 ; i <= n ; ++i) head[i] = 0 , vis[i] = 0;
    for(int i = 1 , u , v ; i < n ; ++i) u = read() , v = read() , add(u , v) , add(v , u);
    dfs(1 , 0);
    cout << f[1] << '\n'; return ;
}

int main()
{
    int T = read();
    while(T--) solve();
    return 0;
}
/*
2

7

1 2

2 3

2 4

4 6

5 6

6 7
7

1 2

2 3

2 4

4 6

5 6

6 7

*/

Guess you like

Origin www.cnblogs.com/R-Q-R-Q/p/12333006.html