bzoj 1596: [Usaco2008 Jan]电话网络【贪心】

dfs,如果一个点的儿子、本身、父亲都没有塔,就在父亲上建一个
原理不明……

#include<iostream>
#include<cstdio>
using namespace std;
const int N=10005;
int n,h[N],cnt,ans;
bool v[N];
struct qwe
{
    int ne,to;
}e[N<<1];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
void add(int u,int v)
{
    cnt++;
    e[cnt].ne=h[u];
    e[cnt].to=v;
    h[u]=cnt;
}
void dfs(int u,int fa)
{
    bool f=0;
    for(int i=h[u];i;i=e[i].ne)
        if(e[i].to!=fa)
        {
            dfs(e[i].to,u);
            if(v[e[i].to])
                f=1;
        }
    if(!f&&!v[u]&&!v[fa])
        ans++,v[fa]=1;
}
int main()
{
    n=read();
    for(int i=1;i<n;i++)
    {
        int x=read(),y=read();
        add(x,y),add(y,x);
    }
    dfs(1,0);
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/8987187.html