1362. Classmates 2

1618 단어 Class
http://acm.timus.ru/problem.aspx?space=1&num=1362
나무 DP
코드:
#include<iostream>

#include<stack>

#include<cstdio>

#include<queue>

#include<cstring>

#include<algorithm>

#include<vector>

#include<set>

#include<map>

#include<string>

#include<cmath>



using namespace std;



typedef long long ll;

typedef pair<int,int> pp;

const int INF=0x3f3f3f3f;

const int N=100002;

int head[N],I;

int d[N];

priority_queue<int>qt[N];

struct node

{

    int j,next;

}edge[N*2];

void add(int i,int j)

{

    edge[I].j=j;

    edge[I].next=head[i];

    head[i]=I++;

}

int dp(int pre,int x)

{

    if(d[x]!=-1)

    return d[x];



    for(int t=head[x];t!=-1;t=edge[t].next)

    {

        int j=edge[t].j;

        if(j==pre)continue;

        qt[x].push(dp(x,j));

    }

    d[x]=0;

    int t=0;

    while(!qt[x].empty())

    {

        ++t;

        d[x]=max(d[x],t+qt[x].top());

        qt[x].pop();

    }

    return d[x];

}

int main()

{

    //freopen("data.in","r",stdin);

    int n;

    cin>>n;

    memset(head,-1,sizeof(head));I=0;

    memset(d,-1,sizeof(d));

    for(int i=1;i<=n;++i)

    {

        int k;

        while(scanf("%d",&k))

        {

            if(k==0) break;

            add(i,k);add(k,i);

        }

    }

    int root;

    cin>>root;

    cout<<dp(-1,root)<<endl;

    return 0;

}


좋은 웹페이지 즐겨찾기