• csuoj-1869-树上最大值


    题目:

    Description

    现在给你一棵根节点编号为1的树,每个节点上都有对应的权值, 求出树上每一层的最大值。(根节点所在位置视为第一层,由此可推,根节点的儿子是处于第二层,etc)

    Input

    多组数据读入 第一行输入一个正整数n表示树上有n个节点(n<=100000),下一行输入n个正整数v1,v2....vn表示n个节点上对应的权值(vi<=100000), 再下一行输入n-1个正整数(第i个数字v表示,节点i+1的父亲是v,保证v<i+1)

    Output

    从树自顶向下输出每一层的最大值是多少,每个值之间用空格隔开,全部输出后末尾换行。

    Sample Input

    6
    10 6 8 7 3 2
    1 2 1 4 4

    Sample Output

    10 7 8
    分析:
    1,添加一个节点时,其深度为父节点深度 + 1;
    2,逐层搜索即可得到每一层的最大值。
    代码:
    #include<iostream>
    #include<cstdio>
    using namespace std;
    struct Node{
        int floor;
        int key;
    }node[100005];
    int val[100005];
    
    int main(){
        int n;
        while(cin >> n){
            for(int i = 1;i <= n;i++){
                scanf("%d",&(node[i].key));
                node[i].floor = 0;
    //            node[i].key = i;
            }
            node[1].floor = 1;
            int maxfloor = 1;
            for(int i = 2;i <= n;i++){
                int temp;
                scanf("%d",&temp);
    //            temp = i - 1;
                node[i].floor = node[temp].floor + 1;
                if(maxfloor < node[i].floor) maxfloor = node[i].floor;
            }
    //        for(int i = 1;i <= n;i++){
    //            cout << i << "  " << node[i].key << "  " << node[i].floor << endl;
    //        }
    //        cout << maxfloor << endl;
            for(int i = 1;i <= maxfloor;i++) val[i] = 100001;
            for(int i = 1;i <= n;i++){
                int floor = node[i].floor;
    //            cout << "floor" << floor << endl;
                if(val[floor] == 100001) val[floor] = node[i].key;
                else if(val[floor] < node[i].key) val[floor] = node[i].key;
            }
            for(int i = 1;i < maxfloor;i++)
                printf("%d ",val[i]);
            printf("%d
    ",val[maxfloor]);
    //            cout << val[i] << " ";
    //        cout << val[maxfloor] << endl;
        }
        return 0;
    }
    
    
     
  • 相关阅读:
    【Uva 10618】Tango Tango Insurrection
    Scripting web services
    防止SQL注入式攻击的笔记
    Net中的Request和Response对象的理解
    Net中的Request和Response对象的理解
    Net中的Request和Response对象的理解
    UEditor编辑器第一次赋值失败的解决方法
    我不问+你不说
    我不问+你不说
    我不问+你不说
  • 原文地址:https://www.cnblogs.com/tracy520/p/6716655.html
Copyright © 2020-2023  润新知