Gym - 101911G - Tree Reconstruction【思维+set】

本文介绍了一种验证特定树结构是否存在的算法,并提供了详细的实现思路与C++代码示例。通过对输入数据的处理和判断,确保了树结构的有效性和正确性。

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

参考大佬的博客,写的很好https://blog.youkuaiyun.com/mmk27_word/article/details/85076236?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160159374419195188335389%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=160159374419195188335389&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v3~pc_rank_v2-5-85076236.first_rank_ecpm_v3_pc_rank_v2&utm_term=Gym±+101911G&spm=1018.2118.3001.4187

题目

传送门
在这里插入图片描述

Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO

题意:给出一个数n,下面是n-1行,每行两个数,分别表示一颗可能存在的树消去第i条边后两段线中最大的顶点.问:这棵树是否存在,存在的话按连接顺序打印n-1行,每行为相连接的顶点.否则输出NO.

思路:首先我们可以确定每一行中应该有一个n,否则树不存在,我们把每行中较小的顶点存起来从小到大连接.

AC code

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<sstream>
#include<queue>
#include<stack>
using namespace std;
set<int>s;
int main()
{
     ios::sync_with_stdio(0);
    int n,a,bb,flag=1,b[1200],c[1200];
   cin>>n;
   for(int i=1;i<n;i++)
     {
         cin>>a>>bb;
         int g=min(a,bb);
         if(a!=n&&bb!=n)flag=0;//每行中一定有一个n
         s.insert(i);
         b[i]=g;//存较小的数
     }
     if(!flag)
     {
         printf("NO\n");
         return 0;
     }
     sort(b+1,b+n);
    c[1]=b[1];
    s.insert(n);
    s.erase(b[1]);
    for(int i=2;i<n;i++)
     {
         if(b[i]==b[i-1])//相等时就看是否还有较小的数
         {
             int p=*s.begin();
             if(p<b[i])
             {
                 c[i]=p;
                 s.erase(p);
             }
               else
               {
                   printf("NO\n");
                   return 0;
               }
         }
         else//不等的话直接连接
         {
            c[i]=b[i];
             s.erase(b[i]);
         }
     }
    c[n]=n;
    printf("YES\n");
    for(int i=2;i<=n;i++)printf("%d %d\n",c[i-1],c[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值