UvaOJ 112 - Tree Summing

本文详细阐述了如何通过给定的二叉树S-expression,判断是否存在指定的根到叶子路径和。重点介绍了使用cin.putback()技巧进行字符缓冲,以及正确识别叶子节点的重要性。通过实例代码,展示了从输入数据中读取并处理的过程。

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

题目

就是给你一个所谓的二叉树的S-expression 让你判断是否存在指定的 根到叶子的路径和。

我在这里用到cin.putback() (C里有 int ungetcA(int ch, FILE *stream) 在cstdio中),方便把下一个字符拿出来判断后再塞回缓冲区,最后用格式化读。

特别注意的是,题目所说的叶子,必须具有(integer()()) 这样的形式才是一个叶子,也就是不是算到() 这里的。开始我一直拿()当路径的结尾,结果就wa了。也是,怎么能拿空节点当叶子呢....好像有点sb...

另外,ac后又测试了下,输入数据中 数字间都没有空格,不是在这里wa的。


代码:

//二叉树,递归。		C里有没有类似 cin.putback(char)  ??

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

#define MAXN 1000002	//没说多少?
int n;
char Rchar()
{
	char t;
	while(scanf("%c", &t) && (t==' ' || t=='\n')){}
	return t;
}
int solve(int root, int sum)		//(3(...)(...))
{
	Rchar();	//'('
	char t = Rchar();
	if(t==')')
	{
		if(sum+root == n) 
		{ 
			char buf[3];
			buf[0] = Rchar();
			buf[1] = Rchar();
			cin.putback(buf[1]);
			cin.putback(buf[0]);
			if(buf[0] == '(' && buf[1] == ')') return 1;		//证明是子叶
			else return 0;
		}
		else return 0;
	}
	cin.putback(t);		//!!!!!!		c 里有没有相应函数?
	int r;	scanf("%d", &r);
	int ret1 = solve(r, sum+root);
	int ret2 = solve(r, sum+root);
	Rchar();	//')'
	return ret1 || ret2;
}

int main()
{
	while(scanf("%d", &n)!=EOF)
	{
		printf(solve(0, 0)? "yes": "no");
		putchar('\n');
	}
}


### 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、付费专栏及课程。

余额充值