1831C - Copil Copac Draws Trees - CodeForces Solution


dfs and similar dp trees

Please click on ads to support us..

Python Code:

import sys,math
import threading
input=sys.stdin.readline
sys.setrecursionlimit(10**8)
def main():
    def dfs(gp,v,c,i):
        if v[i]==1:
            return 0
        v[i]=1
        ans=0
        for x in range(len(gp[i])):
            if gp[i][x][1]<c:
                ans=max(ans,dfs(gp,v,gp[i][x][1],gp[i][x][0])+1)
            else:
                ans=max(ans,dfs(gp,v,gp[i][x][1],gp[i][x][0]))
        return ans
        
    for _ in range(int(input())):
        n=int(input())
                d={1:0}
        ans=1
        gp=[]
        for i in range(n):
            gp.append([])
        for i in range(n-1):
            u,v=map(int,input().split())
            gp[u-1].append([v-1,i])
            gp[v-1].append([u-1,i])
        v=[0]*n
        print(dfs(gp,v,-1,0)+1)
            
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()

C++ Code:

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

#ifdef LOCAL
#include "debug.h"
#else
#define dbg(...) 42
#endif

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int tt;cin >> tt;
	while(tt--){
		int n;
		cin >> n;
		vector<pair<int,int>>adj[n];
		for(int i = 0; i < n - 1; i++){
			int x,y;
			cin >> x >> y;
			--x,--y;
			adj[x].push_back({y,i});
			adj[y].push_back({x,i});
		}
		int a = 1;
		function<void(int,int,int, int )>dfs = [&](int u, int p, int h, int from){
			a = max(a, h);
			for (auto [x,y] : adj[u]){
				if (x == p)continue;
				dfs(x,u,h + (y < from), y);
			}
		};
		dfs(0,0,1,0);
		cout<<a<<'\n';
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

1459B - Move and Turn
1006F - Xor-Paths
706C - Hard problem
304C - Lucky Permutation Triple
1301C - Ayoub's function
38E - Let's Go Rolling
171G - Mysterious numbers - 2
1183C - Computer Game
400C - Inna and Huge Candy Matrix
417A - Elimination
222A - Shooshuns and Sequence
1736A - Make A Equal to B
1736B - Playing with GCD
887C - Solution for Cube
1737C - Ela and Crickets
1741C - Minimize the Thickness
1741A - Compare T-Shirt Sizes
1741D - Masha and a Beautiful Tree
109B - Lucky Probability
1741B - Funny Permutation
1741E - Sending a Sequence Over the Network
344B - Simple Molecules
370A - Rook Bishop and King
546E - Soldier and Traveling
1741G - Kirill and Company
1200B - Block Adventure
1088B - Ehab and subtraction
1270B - Interesting Subarray
478C - Table Decorations
1304C - Air Conditioner