zoukankan      html  css  js  c++  java
  • hihocoder-1851-D级上司

    hihocoder-1851-D级上司 

    #1851 : D级上司

    时间限制:10000ms
    单点时限:1000ms
    内存限制:256MB

    描述

    H公司一共有N名员工,编号为1~N,其中CEO的编号是1。除了CEO之外,每名员工都恰好有唯一的直接上司;N名员工形成了一个树形结构。  

    我们定义X的1级上司是他的直接上司,2级上司是他上司的上司,以此类推……  

    请你找出每名员工的D级上司是谁。

    输入

    第一行包含2个整数N和D。  

    以下N-1行每行包含一个整数,依次代表编号是2-N的员工的直接上司的编号。  

    对于50%的数据,1 ≤ N, D ≤ 10000  

    对于100%的数据,1 ≤ N, D ≤ 100000

    输出

    依次输出1~N的D级上司的编号,每个一行。如果某员工没有D级上司,输出-1。

    样例输入
    5 2   
    1  
    1  
    3  
    3
    样例输出
    -1  
    -1  
    -1  
    1  
    1

    题解:

      1,构建二叉树,并从根节点开始便利;

      2, 利用dfs遍历,并找到其d层祖先。 

    #include <cstdio>   
    #include <iostream> 
    #include <vector> 
    using namespace std; 
    const int MAXN = 100000 + 10;   
    
    int n, k; 
    int ans[MAXN], tmp[MAXN]; 
    vector<int> nd[MAXN]; 
    
    void dfs(int cur_node, int cur_lv)
    {
    	tmp[cur_lv] = cur_node; 
    	if(cur_lv - k > 0)
    	{
    		ans[cur_node] = tmp[cur_lv-k]; 
    	}else{
    		ans[cur_node] = -1; 
    	} 
    	for(int i=0;i<nd[cur_node].size(); ++i)
    	{
    		dfs(nd[cur_node][i], cur_lv+1); 
    	}
    }
    
    int main(){ 
    
        int x; 
        while(scanf("%d %d", &n, &k) != EOF)
        {
        	for(int i=2; i<=n; ++i)
        	{ 
        		scanf("%d", &x); 
        		nd[x].push_back(i); 
        	}  
        	dfs(1, 1);  
        	for(int i=1; i<=n; ++i)
        	{
        		printf("%d
    ", ans[i]);
        	} 
        	for(int i=1; i<=n;++i)
        	{
        		nd[i].clear(); 
        	}
        } 
        return 0; 
    } 
    

      

  • 相关阅读:
    pycharm安装,svn使用,远程开发调试,接口测试,连接服务器
    scrapy回调函数传递参数
    python发送邮件
    python开发部署时新增数据库中表的方法
    python更新数据库脚本三种方法
    python中json.loads,dumps,jsonify使用
    chmod 命令
    find
    find 命令
    locate 命令
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/9819036.html
Copyright © 2011-2022 走看看