2020牛客暑期多校训练营(第二场) C Cover the Tree

假设叶子节点是L个。首先可以证明下界是 L + 1 2 \frac{L+1}{2} 2L+1
所以我们先把叶子节点抽出来,然后通过dfs序排序好。记为 [ 1 , L ] [1,L] [1,L]
然后连接 [ i , i + L 2 ] ( i < = L 2 ) [i,i+\frac{L}{2}](i<=\frac{L}{2}) [i,i+2L](i<=2L)
我们假设有一颗子树,他的叶子节点编号是 [ l , r ] [l,r] [l,r],假设 r < L / 2 rr<L/2那么该子树到根节点的链,肯定会被 [ l , l + L 2 ] [l,l+\frac{L}{2}] [l,l+2L]遍历到,假设 l > L / 2 l>L/2 l>L/2,那么子树到根节点的链肯定会被 [ r − L 2 , r ] [r-\frac{L}{2},r] [r2Lr]遍历到。假设 l < L / 2 ll<L/2&& r > L / 2 r>L/2 r>L/2同理,也会被遍历到。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include
#include
#include 
#pragma GCC optimize(2)
#define up(i,a,b)  for(int i=a;i
#define dw(i,a,b)  for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
    char ch = getchar(); ll x = 0, f = 1;
    while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
    return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 2e5 + 10;
int n;
struct node {
    int next, to;
}edge[N << 1];
int head[N];
int cnt;
void addedge(int u, int v)
{
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
int deg[N];
int dfn[N]; int st;
void dfs(int u, int fa)
{
    dfn[u] = ++st;
    for (int i = head[u]; ~i; i = edge[i].next)
    {
        int v = edge[i].to;
        if (v == fa)continue;
        dfs(v, u);
    }
}
bool cmp(int a, int b)
{
    return dfn[a] < dfn[b];
}
int main()
{
    memset(head, -1, sizeof(head));
    n = read();
    int u, v;
    upd(i, 1, n - 1)
    {
        u = read(), v = read();
        addedge(u, v);
        addedge(v, u);
        deg[u]++;
        deg[v]++;
    }
    if (n == 1)
    {
        printf("0\n"); return 0;
    }
    int root = 1;
    int num = 0;
    vector<int>vec;
    upd(i, 1, n)
    {
        if (deg[i] != 1)
        {
            root = i;
        }
        else vec.push_back(i),num++;
    }
    printf("%d\n", (num + 1) / 2);
    dfs(root, 0);
    sort(vec.begin(), vec.end(), cmp);
    int mid = vec.size() / 2;
    up(i, 0, mid)
    {
        printf("%d %d\n", vec[i], vec[i + mid]);
    }
    if (num & 1)
        printf("%d %d\n", vec.back(), root);
    return 0;
}

你可能感兴趣的:(dfs,多校,思维)