zoukankan      html  css  js  c++  java
  • codeforce580c (dfs)

    题目意思:给你一棵树,然后每个叶子节点会有一家餐馆,你讨厌猫,就不会走有连续超过m个节点有猫的路,然后问你最多去几家饭店

    思路:直接DFS

    Example

    Input
    4 1
    1 1 0 0
    1 2
    1 3
    1 4
    Output
    2
    Input
    7 1
    1 0 1 1 0 0 0
    1 2
    1 3
    2 4
    2 5
    3 6
    3 7
    Output
    2
    #include<iostream>
    #include<algorithm>
    #include<vector>
    #include<string.h>
    #include<math.h>
    using namespace std;
    const int maxn=1e5+6;
    int flag[maxn];
    vector<int>e[maxn];
    int n,m,ans=0;
    void dfs(int u,int num,int fa)
    {
        for(int i=0;i<e[u].size();i++)
        {
            int v=e[u][i];
            if(v==fa)
            continue;
            if(flag[v]==0)
            {
                if(e[v].size()==1)
                ans++;
                dfs(v,0,u); 
            }
            else if(num+1<=m)
            {
                if(e[v].size()==1)
                ans++;
                dfs(v,num+flag[v],u);
            }
        }
    }
    
    int main()
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++)
        cin>>flag[i];
        for(int i=1;i<n;i++)
        {
            int u,v;
            cin>>u>>v;
            e[u].push_back(v);
            e[v].push_back(u);
        }
        dfs(1,flag[1],-1);
        cout<<ans<<endl;
    }
  • 相关阅读:
    c文件操作库
    双链常用操作2
    双向链表常用操作
    c队列操作
    c日期格式化操作之date
    单链常用操作类
    c字符串常用操作
    双向链表通用类
    c栈操作
    poj2509
  • 原文地址:https://www.cnblogs.com/xiechenxi/p/8531058.html
Copyright © 2011-2022 走看看