其他分享
首页 > 其他分享> > [CF1003E] Tree Constructing - 树的直径,构

[CF1003E] Tree Constructing - 树的直径,构

作者:互联网

[CF1003E] Tree Constructing - 树的直径,构造

Description

给n个点,构造一棵树,树的直径是d,每个点连接的点数(度数)不超过k。

Solution

先把直径画出来,然后从上面每个点开始 DFS 出一棵子树来,满足度数限制并不破坏直径条件

#include <bits/stdc++.h>
using namespace std;

#define int long long

int n, d, k;
vector<pair<int, int>> ans;

const int N = 1e6 + 5;
int deg[N], ind;

void make(int p, int q)
{
    deg[p]++;
    deg[q]++;
    ans.push_back({p, q});
}

void dfs(int p, int dep)
{
    if (dep == 0)
        return;
    while (deg[p] < k && ind < n)
    {
        make(p, ++ind);
        dfs(ind, dep - 1);
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin >> n >> d >> k;
    ++d;
    if (d > n)
    {
        cout << "NO" << endl;
        return 0;
    }
    ++ind;
    for (int i = 2; i <= d; i++)
    {
        make(ind, ind + 1);
        ++ind;
    }
    for (int i = 1; i <= d; i++)
    {
        dfs(i, min(i - 1, d - i));
    }

    int flag = 0;
    for (int i = 1; i <= n; i++)
        if (deg[i] > k)
            flag = 1;

    if (ind < n || flag)
    {
        cout << "NO" << endl;
        return 0;
    }

    cout << "YES" << endl;
    for (auto [x, y] : ans)
        cout << x << " " << y << endl;
}

标签:dep,Constructing,int,Tree,++,CF1003E,ind,直径,deg
来源: https://www.cnblogs.com/mollnn/p/14642206.html