D - Root of the Problem思维题

本文介绍了一种通过计算节点值及其子节点值之和来确定二叉树根节点的方法。通过对输入数据进行简单数学运算,可以高效地找出所有可能的根节点ID。

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


那么简单的题目,自己居然不会做,真想给自己两巴掌清醒一下。。。简单思维题,将所有点的值加起来,再将所有总值的点加起来,那么它们的差就是根节点的值,因为所有总值的点是没有一个点包含根节点的!!!!


Chef has a binary tree. The binary tree consists of 1 or more nodes. Each node has a unique integer id. Each node has up to 2 children, which are identified by their ids, and each node is the child of at most 1 other node. A node X is considered to be an ancestor of node Y if node Y is a child of node X or if there is some node Z for which X is an ancestor of Z and Y is a child of Z. No node is an ancestor of itself. A special node called the root node is an ancestor of all other nodes.

Chef has forgotten which node of his tree is the root, and wants you to help him to figure it out. Unfortunately, Chef's knowledge of the tree is incomplete. He does not remember the ids of the children of each node, but only remembers the sum of the ids of the children of each node.

Input

Input begins with an integer T, the number of test cases. Each test case begins with an integer N, the number of nodes in the tree. N lines follow with 2 integers each: the id of a node, and the sum of the ids of its children. The second number will be 0 if the node has no children.

Output

For each test case, output on a line a space separated list of all possible values for the id of the root node in increasing order. It is guaranteed that at least one such id exists for each test case.

Constraints

  • 1 ≤ T ≤ 50
  • 1 ≤ N ≤ 30
  • All node ids are between 1 and 1000, inclusive

Sample Input

2
1
4 0
6
1 5
2 0
3 0
4 0
5 5
6 5


#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
int a[5009];
long long num=4294967296-1;
int main()
{
    int n,t,a,b;
    scanf("%d",&t);
    while(t--)
    {
        int sum1=0;
        int sum2=0;
        scanf("%d",&n);
        while(n--)
        {
            scanf("%d%d",&a,&b);
            sum1+=a;
            sum2+=b;
        }
        printf("%d\n",sum1-sum2);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值