CodeForce - 1014E - Tree Reconstruction greedy

Keywords: less

Title Link

Meaning: a tree has n nodes. Now there are n-1 states. The ith state means to delete the ith edge. Each state has two numbers a and b. Represents the largest node of two trees formed after deleting the i-th edge. To find out whether there is such a tree for known n-1 States, if there is such a tree, the edges will be output at the same time.

Idea: because there must be n in each state, just look at another node. Count the number of times each node appears num. It can be found that if num[3]=3, then the tree can be n-1-2-3, if num[3]=2, then it can be 2-n-1-3, and so on, then we can regard n as the root of the tree, each node to the root of the tree n is in the form of chain, and there is no branch, so we can get that if num[i]!=0, then the distance from I to the root of the tree n is num[i], and the points on the path are less than I and num is 0, so we can go from greedy Angle, traverse num=0 from small to large, and traverse num!=0 from small to large. Insert the previous traversal node between N and the next traversal node.

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define PI acos(-1)
#define INF 0x3f3f3f3f
#define NUM 50010
#define debug true
#define lowbit(x) ((-x)&x)
#define ffor(i,d,u) for(int i=d;i<=u;++i)
#define _ffor(i,u,d) for(int i=u;i>=d;--i)
#define mst(array,Num) memset(array,Num,sizeof(array))
const int p = 1e9+7;
int n;
int a[1100];
struct ANS
{
    int from,to;
}ans[1100];
int que[1100],head,tail;
int tot=0;
template <typename T>
void read(T &x){
    char ch = getchar();x = 0;
    for (; ch < '0' || ch > '9'; ch = getchar());
    for (; ch >='0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
}
template <typename T>
void write(T x)
{
    int len=0;char c[21];
    if(x<0)putchar('-'),x*=(-1);
    do{++len;c[len]=(x%10)+'0';}while(x/=10);
    _ffor(i,len,1)putchar(c[i]);
}
inline void AC()
{
    int x,y;
    mst(a,0);
    read(n);
    ffor(i,1,n-1)
    {
        read(x),read(y);
        ++a[x],++a[y];
    }
    if(a[n]!=n-1)
    {
        puts("NO");
        return ;
    }
    int j;
    head=1,tail=0;
    ffor(i,1,n-1)
        if(a[i]==0)
            que[++tail]=i;
        else
        {
            j=n,--a[i];
            while(head<=tail&&a[i]!=0)
            {
                x=que[head++];
                if(x>i)break;
                ans[++tot].from=j,ans[tot].to=x,--a[i];
                j=x;
            }
            if(a[i]!=0)
            {
                puts("NO");
                return ;
            }
            ans[++tot].from=j,ans[tot].to=i;
        }
    puts("YES");
    ffor(i,1,n-1)write(ans[i].from),putchar(' '),write(ans[i].to),putchar('\n');
}
int main()
{
    AC();
    return 0;
}

 

Posted by bonkaz on Mon, 30 Dec 2019 11:45:03 -0800