1385F - Removing Leaves - CodeForces Solution


data structures greedy implementation trees *2300

Please click on ads to support us..

C++ Code:

// Hydro submission #64df1d3896648c256e881d4d@1692345553318
#include<bits/stdc++.h>
using namespace std;

int n,k;
set<int> to[200001],leaf[200001];
priority_queue<pair<int,int> > Q;

void init(int id,int father){
    for(int v :to[id])
        if(v!=father){
            init(v,id);
            if(to[v].size()==1)
                leaf[id].insert(v);
        }
    if(to[id].size()==1)
        for(int v :to[id])
            if(v!=father){
                init(v,id);
                leaf[v].insert(id);
            }
}

int main(){
    int T; scanf("%d",&T);
    while(T--){
        while(!Q.empty())Q.pop();
        scanf("%d%d",&n,&k);
        for(int i=1;i<=n;i++)
            to[i].clear(),leaf[i].clear();
        for(int i=1;i<n;i++){
            int u,v;
            scanf("%d%d",&u,&v);
            to[u].insert(v);
            to[v].insert(u);
        }
        if(k==1){
            printf("%d\n",n-1);
            continue;
        }
        init(1,0);
        for(int i=1;i<=n;i++)
            if(leaf[i].size()>=k)
                Q.push({leaf[i].size(),i});
        int total=0;
        while(!Q.empty()){
            int u=Q.top().second; Q.pop();
            while(leaf[u].size()>=k){
                for(int i=1;i<=k;i++)
                    to[u].erase(*(leaf[u].begin())),
                    leaf[u].erase(leaf[u].begin());
                total++;
            }
            if(to[u].size()==1){
                int fa=*(to[u].begin());
                leaf[fa].insert(u);
                if(leaf[fa].size()>=k)
                    Q.push({leaf[fa].size(),fa});
            }
        }
        printf("%d\n",total);
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1426C - Increase and Copy
520C - DNA Alignment
767A - Snacktower
1365A - Matrix Game
714B - Filya and Homework
31A - Worms Evolution
1691A - Beat The Odds
433B - Kuriyama Mirai's Stones
892A - Greed
32A - Reconnaissance
1236D - Alice and the Doll
1207B - Square Filling
1676D - X-Sum
1679A - AvtoBus
1549A - Gregor and Cryptography
918C - The Monster
4B - Before an Exam
545B - Equidistant String
1244C - The Football Season
1696B - NIT Destroys the Universe
1674A - Number Transformation
1244E - Minimizing Difference
1688A - Cirno's Perfect Bitmasks Classroom
219A - k-String
952A - Quirky Quantifiers
451B - Sort the Array
1505H - L BREAK into program
171E - MYSTERIOUS LANGUAGE
630D - Hexagons
1690D - Black and White Stripe