1325C - Ehab and Path-etic MEXs - CodeForces Solution


constructive algorithms dfs and similar greedy trees *1500

Please click on ads to support us..

Python Code:

n = int(input());jaya= [0]*(n+1);l = []
for i in range(n-1):
	a,b = map(int,input().split());a -= 1;b -= 1;jaya[a] += 1;jaya[b] += 1;l.append([a,b])
m = 0;mex = n-2
for a,b in l:
	if jaya[a] == 1 or jaya[b] == 1:print(m);m+= 1
	else:print(mex);mex -= 1

C++ Code:

#include <bits/stdc++.h>
using namespace std;
void solve_task(){
    int n;
    scanf("%d", &n);
    int cnt[n];
    memset(cnt,0,sizeof cnt);
    vector< pair<int, int> > ed[n];
    for(int i=1;i<n;i++){
        int a,b;
        scanf("%d%d",&a,&b);
        a--,b--;
        ed[a].push_back({b,i});
        ed[b].push_back({a,i});
    }
    int nxt=0,ans[n],vis[n];
    memset(ans,-1,sizeof ans);
    memset(vis,0,sizeof vis);
    queue<int> q;
    for(int i=0;i<n;i++){
        if(ed[i].size()>1)continue;
        q.push(i);
        vis[i]=1;
    }
    for(;!q.empty();q.pop()){
        auto i=q.front();
        for(auto [j,pos]:ed[i]){
            if(ans[pos]==-1)ans[pos]=nxt++;
            if(!vis[j]){
                q.push(j);
                vis[j]=1;
            }
        }
    }
    for(int i=1;i<n;i++){
        printf("%d\n",ans[i]);
    }
}
int main(){
    int t = 1;
    while(t--){
        solve_task();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1466C - Canine poetry
74A - Room Leader
1333D - Challenges in school №41
1475B - New Year's Number
461A - Appleman and Toastman
320B - Ping-Pong (Easy Version)
948A - Protect Sheep
387A - George and Sleep
53A - Autocomplete
1729G - Cut Substrings
805B - 3-palindrome
805C - Find Amir
676C - Vasya and String
1042B - Vitamins
1729F - Kirei and the Linear Function
25D - Roads not only in Berland
1694A - Creep
659F - Polycarp and Hay
1040A - Palindrome Dance
372A - Counting Kangaroos is Fun
1396B - Stoned Game
16A - Flag
1056A - Determine Line
670B - Game of Robots
1418C - Mortal Kombat Tower
1382B - Sequential Nim
1272C - Yet Another Broken Keyboard
808A - Lucky Year
1245A - Good ol' Numbers Coloring
58B - Coins