zoukankan      html  css  js  c++  java
  • BZOJ 1907: 树的路径覆盖

    dfs时往上贪心。贪心的正确性略过(应该很显然吧。。)

    #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] << '
    '; 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
    
    */
    
  • 相关阅读:
    Window 中的自带方法Base64
    React_Class1
    npm 常用操作
    React__生命周期
    axios 简单方法个人理解
    JavaScript_Window对象
    常见的搜索引擎技巧
    JS_String常见问题Demo
    java调用C++代码
    java虚拟机指令dup的理解
  • 原文地址:https://www.cnblogs.com/R-Q-R-Q/p/12333006.html
Copyright © 2011-2022 走看看