UVA 112 Tree Summing

本文深入探讨了一个利用树结构解决问题的实例,具体阐述了如何通过转换字符串来构建树,并在给定路径求和条件下判断是否存在特定路径。通过实例分析,读者将了解到树的基本操作、递归思想的应用以及如何解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

~~题目链接~~


题目大意:用()表示空节点, (5)表示一个为5的节点, 5()() 表示叶子节点, 5(2)(6)表示当前节点为5, 左节点为2,右节点为6.现在给出一串字符串, 求是否有根节点到叶节点的值等于给定的值。



code:

#include <iostream>
#include <algorithm>
using namespace std;

typedef struct node
{
    int num;
    struct node *lf, *rt;
}Node;

int n = 0, ans = 0;

int trans(string &s, int &start)//转换为数字
{
    int flag = 0, sum = 0;
    if(s[start] == '-') flag = 1, start++;
    else sum += s[start++]-'0';
    while(s[start] != '(' && s[start] != ')')
    {
        sum *= 10;
        sum += s[start++]-'0';
    }
    if(flag) sum = -sum;
    return sum;
}

int build(Node *r, string &s,int &cur, int sum)
{
    int cur_sum = 0;
    r->lf = new Node;
    r->rt = new Node;

    if(s[cur] == ')' && s[cur+1] == '(' && s[cur+2] == ')')//上一个节点为叶子节点
    {
        cur += 3;
        return 1;
    }
    else if(s[cur] != '(' && s[cur] != ')')
        r->num = trans(s, cur);

    cur_sum = sum+r->num;
    if(s[cur] == '(')//左子树
       if(build(r->lf, s, ++cur, cur_sum))//为叶节点判断
       {
           if(cur_sum == n)
               ans = 1;
       }

    if(s[cur] == '(')//右子树
       if(build(r->rt, s, ++cur, cur_sum))
        if(cur_sum == n) ans = 1;
    if(s[cur] == ')') cur++;
    return 0;
}

int main()
{
    int i = 0, j = 0, num = 0, flag = 1;//flag判断读取树没
    string s, res;
    while(cin>>n)
    {
        num = ans = 0;
        Node *r = new Node;
        res = "";//为最终的字符串
        do
        {
            getline(cin, s);
            string::iterator it = remove(s.begin(),s.end(), ' ');
            s.erase(it, s.end());
            for(i = 0; i<s.size(); i++)
                if(s[i] == '(') num++, flag = 0;
                else if(s[i] == ')') num--;
            res += s;
        }
        while(num || flag);
        if(res[1] != ')')//读出根节点的数
        {
            i = 1;
            r->num = trans(res, i);
            res.erase(res.end()-1);
            res.erase(res.begin(), res.begin()+i);
        }
        i = 0;
        build(r, res, i, 0);
        if(ans) cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
    return 0;
}


### USACO 2016 January Contest Subsequences Summing to Sevens Problem Solution and Explanation In this problem from the USACO contest, one is tasked with finding the size of the largest contiguous subsequence where the sum of elements (IDs) within that subsequence is divisible by seven. The input consists of an array representing cow IDs, and the goal is to determine how many cows are part of the longest sequence meeting these criteria; if no valid sequences exist, zero should be returned. To solve this challenge efficiently without checking all possible subsequences explicitly—which would lead to poor performance—a more sophisticated approach using prefix sums modulo 7 can be applied[^1]. By maintaining a record of seen remainders when dividing cumulative totals up until each point in the list by 7 along with their earliest occurrence index, it becomes feasible to identify qualifying segments quickly whenever another instance of any remainder reappears later on during iteration through the dataset[^2]. For implementation purposes: - Initialize variables `max_length` set initially at 0 for tracking maximum length found so far. - Use dictionary or similar structure named `remainder_positions`, starting off only knowing position `-1` maps to remainder `0`. - Iterate over given numbers while updating current_sum % 7 as you go. - Check whether updated value already exists inside your tracker (`remainder_positions`). If yes, compare distance between now versus stored location against max_length variable's content—update accordingly if greater than previous best result noted down previously. - Finally add entry into mapping table linking latest encountered modulus outcome back towards its corresponding spot within enumeration process just completed successfully after loop ends normally. Below shows Python code implementing described logic effectively handling edge cases gracefully too: ```python def find_largest_subsequence_divisible_by_seven(cow_ids): max_length = 0 remainder_positions = {0: -1} current_sum = 0 for i, id_value in enumerate(cow_ids): current_sum += id_value mod_result = current_sum % 7 if mod_result not in remainder_positions: remainder_positions[mod_result] = i else: start_index = remainder_positions[mod_result] segment_size = i - start_index if segment_size > max_length: max_length = segment_size return max_length ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值