洛谷P2018 消息传递

P2018 消息传递

题目描述

巴蜀国的社会等级森严,除了国王之外,每个人均有且只有一个直接上级,当然国王没有上级。如果A是B的上级,B是C的上级,那么A就是C的上级。绝对不会出现这样的关系:A是B的上级,B也是A的上级。

最开始的时刻是0,你要做的就是用1单位的时间把一个消息告诉某一个人,让他们自行散布消息。在任意一个时间单位中,任何一个已经接到消息的人,都可以把消息告诉他的一个直接上级或者直接下属。

现在,你想知道:

1.到底需要多长时间,消息才能传遍整个巴蜀国的所有人?

2.要使消息在传递过程中消耗的时间最短,可供选择的人有那些?

输入输出格式

输入格式:

输入文件的第一行为一个整数N(N≤1000),表示巴蜀国人的总数,假如人按照1到n编上了号码,国王的编号是1。第2行到第N行(共N-1行),每一行一个整数,第i行的整数表示编号为i的人直接上级的编号。

输出格式:

文件输出共计两行:

第一行为一个整数,表示最后一个人接到消息的最早时间。

第二行有若干个数,表示可供选择人的编号,按照编号从小到大的顺序输出,中间用空格分开。

输入输出样例

输入样例#1:
8
1
1
3
4
4
4
3
输出样例#1:
5
3 4 5 6 7
/*
    树形dp
    思路:枚举第一个放的位置,dfs递归处理出当前节点u的子节点v需要的传递时间,然后从大到小排序,对于传递时间长的节点,就先传递给它。
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 1010
using namespace std;
int ans=0x7fffffff,an[maxn],dp[maxn],n,num,head[maxn],ans_num;
struct node{
    int pre,to;
}e[maxn*2];
void Insert(int from,int to){
    e[++num].to=to;
    e[num].pre=head[from];
    head[from]=num;
}
void dfs(int now,int father){
    int cnt=0,tmp[maxn];
    for(int i=head[now];i;i=e[i].pre){
        int to=e[i].to;
        if(to==father)continue;
        dfs(to,now);
        tmp[++cnt]=dp[to];
    }
    sort(tmp+1,tmp+cnt+1);
    for(int i=1;i<=cnt;i++)dp[now]=max(dp[now],tmp[i]+cnt-i+1);
}
int main(){
    freopen("Cola.txt","r",stdin);
    scanf("%d",&n);
    int x;
    for(int i=2;i<=n;i++){
        scanf("%d",&x);
        Insert(x,i);
        Insert(i,x);
    }
    for(int i=1;i<=n;i++){
        memset(dp,0,sizeof(dp));
        dfs(i,0);
        if(ans>dp[i]){
            ans=dp[i];
            ans_num=0;
        }
        if(ans==dp[i])an[++ans_num]=i;
    }
    printf("%d
",ans+1);
    for(int i=1;i<=ans_num;i++)printf("%d ",an[i]);
    return 0;
}
原文地址:https://www.cnblogs.com/thmyl/p/7412814.html