紫书 The Falling Leaves UVA - 699 递归得简单

Posted COLORFUL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了紫书 The Falling Leaves UVA - 699 递归得简单相关的知识,希望对你有一定的参考价值。

题意:给你一颗二叉树的前序遍历,空子树以-1表示,将左右子树的权值投影到一维数轴上,左儿子位置为根位置-1,右儿子+1求个个整点上的和;

题解:递归,整个过程只需维护一个sum数组。

    更新根,更新leftson ,更新rightson;

代码:

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include<stdio.h>
#include<algorithm>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<iostream>
#include<string.h>
#include<queue>
#include<string>
#include<sstream>
using namespace std;
const int maxn = 80+5;
int sum[maxn],p;
void build(int p) {//更新以p为根的树对sum的贡献:更新根,更新leftson ,更新right son;
    int v; cin >> v;
    if (v == -1)return;
    sum[p] += v;
    build(p - 1); build(p + 1);
}
bool init() {
    int v;
    cin >> v;
    if (v == -1)return false;
    memset(sum, 0, sizeof(sum));
    int pos = maxn / 2;
    sum[pos] = v;
    build(pos - 1); build(pos + 1);
}
int main(){
    int kase = 0;
    while (init()) {
        int p = 0;
        while (sum[p] == 0)p++;
        cout << "Case " << ++kase << ":\n" << sum[p++];
        while (sum[p] != 0)cout << " " << sum[p++];
        cout << "\n\n";
    }
    //system("pause");
    return 0;
}

 

以上是关于紫书 The Falling Leaves UVA - 699 递归得简单的主要内容,如果未能解决你的问题,请参考以下文章

UVA 699 The Falling Leaves

UVA699 UVALive5471 The Falling Leaves树权和

下落的树叶 (The Falling Leaves UVA - 699)

The Falling Leaves UVA - 699

UVa 699 The Falling Leaves(递归建树)

Uva 699The Falling Leaves