Codeforces 1283F DIY Garland

题目链接:

Codeforces 1283F DIY Garland

思路:

用一个数组保存所有结点度数,从后往前扫题目给的数组,[loop][根据贪心思想,每次匹配当前结点和度数为1的结点里序号最小的那个形成一条边,由于是从后往前扫,则我们是从叶子往根部推,因此匹配完这次后可以剪掉这条边不在考虑,算法上的体现就是两者度数都减一]

代码:

#include<bits/stdc++.h>

using namespace std;

const int maxn = 2e5+5;
int n, a[maxn], deg[maxn];

int main(){
//    freopen("Sakura.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i++) deg[i] = 1;
    for(int i = 0; i < n-1; i++){
        cin >> a[i];
        deg[a[i]]++;
    }
    cout << a[0] << '\n';
    priority_queue<int, vector<int>, greater<int> > que;
    for(int i = 1; i <= n; i++) if(deg[i] == 1) que.push(i);
    int tmp = n - 2;
    while(tmp>=0){
        int x = a[tmp--], y = que.top();
        que.pop();
        cout << x << ' ' << y << '\n';
        --deg[x], --deg[y];
        if(deg[x] == 1) que.push(x);
    }
    return 0;
}

发布了281 篇原创文章 · 获赞 7 · 访问量 6735

猜你喜欢

转载自blog.csdn.net/qq_45228537/article/details/103786017