UVA 112 - Tree Summing(栈)

本文详细分析了在解决UVA与北大平台上的特定编程问题时,如何利用栈数据结构高效处理括号匹配与输入解析。通过对比不同平台的反馈,探讨了在实现细节上的微妙差异及其原因。

        又是一道让我心碎的题。UVA上提交了10几次都错了,在北大上又过了。用栈做的,在处理输入和判断括号上感觉还蛮良好的。

#include <stdio.h>
#include <string.h>
#define MAXN 10000

int stack[MAXN];
int topc, top, t;

bool judge() {
    int sum = 0;
    for (int i=1; i<=top; i++)
        sum += stack[i];
    if (sum == t)
        return true;
    return false;
}

int main() {

    //freopen("f:\\out.txt", "w", stdout);
    while (scanf("%d", &t) != EOF) {
        int tmp = 0, flag = 0, isNeg = 0;
        char pre[4];
        topc = top = 0;
        memset(pre, 0, sizeof (pre));

        while (1) {
            // 接收字符的代码,忽略掉空格和换行
            char ch = getchar();
            while ('\n'==ch || ' '==ch)
                ch = getchar();

            // 记录该字符前三个字符,便于判断是否为叶子
            pre[3] = pre[2];
            pre[2] = pre[1];
            pre[1] = pre[0];
            pre[0] = ch;

            // 如果遇到左括弧就进栈
            if ('(' == ch) {
                topc++;
                if (tmp) {
                    if (isNeg) {
                        tmp *= -1;
                        isNeg = 0;
                    }
                    stack[++top] = tmp;
                    tmp = 0;
                }
                continue;
            }

            // 如果遇到右括弧就出栈
            if (')' == ch) {
                // 如果为叶子便计算
                if ('('==pre[1] && ')'==pre[2] && '('==pre[3]) {
                    if (!flag)
                        flag = judge();
                }
                else if (pre[1] != '('){
                    top--;
                }
                topc--;
                // 如果左括弧都被匹配完说明二叉树输入完毕
                if (!topc)
                    break;
                continue;
            }
            if ('-' == ch)
                isNeg = 1;
            else
                tmp = tmp*10 + (ch-'0');
        }

        if (flag)
            printf("yes\n");
        else
            printf("no\n");
    }

    return 0;
}

下面是一个牛人的代码,膜拜。忘了在哪找的了。

#include<iostream>
using namespace std;
bool ok;
bool tree_sum(int n,int sum)
{
    int v;
    char ch;
    cin>>ch;
    if(!((cin>>v)==0))
    {
        n+=v;
        bool t=tree_sum(n,sum)|tree_sum(n,sum);
        if(!ok&&!t)
            ok=(n==sum);
        cin>>ch;
        return true;
    }
    else
    {
        cin.clear();//消除错误状态
        cin>>ch;
        return false;
    }
}
int main()
{
    // freopen("f:\\out.txt", "w", stdout);
    int sum;
    while(cin>>sum)
    {
        ok=false;
        tree_sum(0,sum);
        cout<<(ok?"yes":"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、付费专栏及课程。

余额充值