puwaer/puwaer_code_translation huggingface dataset:
AtCoder problem 002

C++ solution:
// this problem was so fun :)

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

#define fs(n) fixed << setprecision(n);
#define mp(a, b) make_pair(a, b);
using ll = long long;
using ld = long double;

int n;
int l = 0, r = 0;
vector<string> anslist;

/*
  if X is correct brackets string then:
  (define length of X = L)
  * L is even number
  * from 1st to nth chars,
  *   the count of "(" is greater than or equal to the count of ")" (1 ~ n ~ L - 1)
  * the total count of "(" is equal to the total count of ")" is equal to L / 2
*/
void dfs(string s){
  if(s.length() == n){
    // should consist l = r = n / 2
    anslist.emplace_back(s);
    return;
  }else{
    if(r < n / 2){
      r++;
      dfs(s + "(");
      r--;
    }
    if(l < n / 2 && r > l){
      l++;
      dfs(s + ")");
      l--;
    }
  }
}

int main(){
  // amount of "(" is equal to amount of ")" is equal to n / 2
  cin >> n;
  if(n % 2) cout << endl;
  else{
    // generate from 2nd char by dfs
    r = 1;
    dfs("(");
  }
  // sort by lexical order ('(' < ')')
  sort(anslist.begin(), anslist.end());
  for(auto itr = anslist.begin(); itr != anslist.end(); itr++){
    cout << *itr << endl;
  }
}






Ruby solution: def solve(s, n, depth)
    if n == 0 then
        puts s
    else
        solve(s + '(', n - 1, depth + 1) if depth < n
        solve(s + ')', n - 1, depth - 1) if depth > 0
    end
end

n = readline.to_i
solve('', n , 0) if n % 2 == 0
AtCoder problem 002

C++ solution:
// this problem was so fun :)

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

#define fs(n) fixed << setprecision(n);
#define mp(a, b) make_pair(a, b);
using ll = long long;
using ld = long double;

int n;
int l = 0, r = 0;
vector<string> anslist;

/*
  if X is correct brackets string then:
  (define length of X = L)
  * L is even number
  * from 1st to nth chars,
  *   the count of "(" is greater than or equal to the count of ")" (1 ~ n ~ L - 1)
  * the total count of "(" is equal to the total count of ")" is equal to L / 2
*/
void dfs(string s){
  if(s.length() == n){
    // should consist l = r = n / 2
    anslist.emplace_back(s);
    return;
  }else{
    if(r < n / 2){
      r++;
      dfs(s + "(");
      r--;
    }
    if(l < n / 2 && r > l){
      l++;
      dfs(s + ")");
      l--;
    }
  }
}

int main(){
  // amount of "(" is equal to amount of ")" is equal to n / 2
  cin >> n;
  if(n % 2) cout << endl;
  else{
    // generate from 2nd char by dfs
    r = 1;
    dfs("(");
  }
  // sort by lexical order ('(' < ')')
  sort(anslist.begin(), anslist.end());
  for(auto itr = anslist.begin(); itr != anslist.end(); itr++){
    cout << *itr << endl;
  }
}





Kuin solution: func main()
	var n: int :: cui@inputInt()
	if(n % 2 <> 0)
		do cui@print("\n")
		ret
	end if
	
	for i(0, 2 ^ n - 1)
		var id: int :: i
		var cntOpen: int :: 0
		var cntClose: int :: 0
		var a: []bool :: #[n]bool
		for j(0, n - 1)
			do a[j] :: id % 2 = 1
			if(a[j])
				do cntOpen :+ 1
				if(cntOpen > n / 2)
					skip i
				end if
			else
				do cntClose :+ 1
				if(cntClose > cntOpen)
					skip i
				end if
			end if
			do id :/ 2
		end for
		for j(n - 1, 0, -1)
			do cui@print(a[j] ?(")", "("))
		end for
		do cui@print("\n")
	end for
end func
AtCoder problem 002

C++ solution:

Crystal solution: n = read_line.to_i
['(', ')'].each_repeated_permutation(n, true) { |s|
  a = s.reduce([0]) { |acc, c|
    acc << acc[-1] + (c == '(' ? 1 : -1)
  }
  if a[-1] == 0 && a.all? { |i| i >= 0 }
    puts s.join
  end
}


Python solution: from itertools import product
n = int(input())
ans = []

if n % 2 == 0: # 奇数のときは正しいカッコ列を生成できない
    for i in product([0, 1], repeat = n): # 0 -> （ , 1 -> ）
        if i.count(1) == n // 2: # 0, 1の個数が同じ時に判定を始める
            zero_count = 0
            Bool = True
            word = ""
            for j in range(len(i)):
                if i[j] == 0:
                    zero_count += 1
                elif i[j] == 1:
                    if zero_count >= 1: # 0の個数が１個以上ないと正しい文字列にならない
                        zero_count -= 1
                    else:
                        Bool = False
                word += str(i[j])
            if Bool:
                x = word.replace("0", "(")
                y = x.replace("1", ")")
                ans.append(y)
ans.sort()
print(*ans ,sep = "\n")
AtCoder problem 002

C++ solution:

Crystal solution: n = read_line.to_i
['(', ')'].each_repeated_permutation(n, true) { |s|
  a = s.reduce([0]) { |acc, c|
    acc << acc[-1] + (c == '(' ? 1 : -1)
  }
  if a[-1] == 0 && a.all? { |i| i >= 0 }
    puts s.join
  end
}






Ruby solution: def solve(s, n, depth)
    if n == 0 then
        puts s
    else
        solve(s + '(', n - 1, depth + 1) if depth < n
        solve(s + ')', n - 1, depth - 1) if depth > 0
    end
end

n = readline.to_i
solve('', n , 0) if n % 2 == 0
AtCoder problem 002

C++ solution:

Crystal solution: n = read_line.to_i
['(', ')'].each_repeated_permutation(n, true) { |s|
  a = s.reduce([0]) { |acc, c|
    acc << acc[-1] + (c == '(' ? 1 : -1)
  }
  if a[-1] == 0 && a.all? { |i| i >= 0 }
    puts s.join
  end
}





Kuin solution: func main()
	var n: int :: cui@inputInt()
	if(n % 2 <> 0)
		do cui@print("\n")
		ret
	end if
	
	for i(0, 2 ^ n - 1)
		var id: int :: i
		var cntOpen: int :: 0
		var cntClose: int :: 0
		var a: []bool :: #[n]bool
		for j(0, n - 1)
			do a[j] :: id % 2 = 1
			if(a[j])
				do cntOpen :+ 1
				if(cntOpen > n / 2)
					skip i
				end if
			else
				do cntClose :+ 1
				if(cntClose > cntOpen)
					skip i
				end if
			end if
			do id :/ 2
		end for
		for j(n - 1, 0, -1)
			do cui@print(a[j] ?(")", "("))
		end for
		do cui@print("\n")
	end for
end func
AtCoder problem 002

C++ solution:


Python solution: from itertools import product
n = int(input())
ans = []

if n % 2 == 0: # 奇数のときは正しいカッコ列を生成できない
    for i in product([0, 1], repeat = n): # 0 -> （ , 1 -> ）
        if i.count(1) == n // 2: # 0, 1の個数が同じ時に判定を始める
            zero_count = 0
            Bool = True
            word = ""
            for j in range(len(i)):
                if i[j] == 0:
                    zero_count += 1
                elif i[j] == 1:
                    if zero_count >= 1: # 0の個数が１個以上ないと正しい文字列にならない
                        zero_count -= 1
                    else:
                        Bool = False
                word += str(i[j])
            if Bool:
                x = word.replace("0", "(")
                y = x.replace("1", ")")
                ans.append(y)
ans.sort()
print(*ans ,sep = "\n")




Ruby solution: def solve(s, n, depth)
    if n == 0 then
        puts s
    else
        solve(s + '(', n - 1, depth + 1) if depth < n
        solve(s + ')', n - 1, depth - 1) if depth > 0
    end
end

n = readline.to_i
solve('', n , 0) if n % 2 == 0
AtCoder problem 002

C++ solution:


Python solution: from itertools import product
n = int(input())
ans = []

if n % 2 == 0: # 奇数のときは正しいカッコ列を生成できない
    for i in product([0, 1], repeat = n): # 0 -> （ , 1 -> ）
        if i.count(1) == n // 2: # 0, 1の個数が同じ時に判定を始める
            zero_count = 0
            Bool = True
            word = ""
            for j in range(len(i)):
                if i[j] == 0:
                    zero_count += 1
                elif i[j] == 1:
                    if zero_count >= 1: # 0の個数が１個以上ないと正しい文字列にならない
                        zero_count -= 1
                    else:
                        Bool = False
                word += str(i[j])
            if Bool:
                x = word.replace("0", "(")
                y = x.replace("1", ")")
                ans.append(y)
ans.sort()
print(*ans ,sep = "\n")



Kuin solution: func main()
	var n: int :: cui@inputInt()
	if(n % 2 <> 0)
		do cui@print("\n")
		ret
	end if
	
	for i(0, 2 ^ n - 1)
		var id: int :: i
		var cntOpen: int :: 0
		var cntClose: int :: 0
		var a: []bool :: #[n]bool
		for j(0, n - 1)
			do a[j] :: id % 2 = 1
			if(a[j])
				do cntOpen :+ 1
				if(cntOpen > n / 2)
					skip i
				end if
			else
				do cntClose :+ 1
				if(cntClose > cntOpen)
					skip i
				end if
			end if
			do id :/ 2
		end for
		for j(n - 1, 0, -1)
			do cui@print(a[j] ?(")", "("))
		end for
		do cui@print("\n")
	end for
end func
AtCoder problem 002

C++ solution:





Kuin solution: func main()
	var n: int :: cui@inputInt()
	if(n % 2 <> 0)
		do cui@print("\n")
		ret
	end if
	
	for i(0, 2 ^ n - 1)
		var id: int :: i
		var cntOpen: int :: 0
		var cntClose: int :: 0
		var a: []bool :: #[n]bool
		for j(0, n - 1)
			do a[j] :: id % 2 = 1
			if(a[j])
				do cntOpen :+ 1
				if(cntOpen > n / 2)
					skip i
				end if
			else
				do cntClose :+ 1
				if(cntClose > cntOpen)
					skip i
				end if
			end if
			do id :/ 2
		end for
		for j(n - 1, 0, -1)
			do cui@print(a[j] ?(")", "("))
		end for
		do cui@print("\n")
	end for
end func


Ruby solution: def solve(s, n, depth)
    if n == 0 then
        puts s
    else
        solve(s + '(', n - 1, depth + 1) if depth < n
        solve(s + ')', n - 1, depth - 1) if depth > 0
    end
end

n = readline.to_i
solve('', n , 0) if n % 2 == 0
AtCoder problem 003

C++ solution:
#include <iostream>

#include <vector>

#include <queue>

using namespace std;



// 入力

int N;

int A[1 << 18], B[1 << 18];



// グラフ

const int INF = (1 << 29);

vector<int> G[1 << 18];

int dist[1 << 18];



void getdist(int start) {

	// 幅優先探索（BFS）により、最短距離を計算

	for (int i = 1; i <= N; i++) dist[i] = INF;



	queue<int> Q;

	Q.push(start);

	dist[start] = 0;



	while (!Q.empty()) {

		int pos = Q.front(); Q.pop();

		for (int to : G[pos]) {

			if (dist[to] == INF) {

				dist[to] = dist[pos] + 1;

				Q.push(to);

			}

		}

	}

}



int main() {

	// Step #1. 入力

	cin >> N;

	for (int i = 1; i <= N - 1; i++) {

		cin >> A[i] >> B[i];

		G[A[i]].push_back(B[i]);

		G[B[i]].push_back(A[i]);

	}



	// Step #2. 頂点 1 からの最短距離を求める

	// maxid1: 頂点 1 から最も離れている（最短距離が長い）頂点

	getdist(1);

	int maxn1 = -1, maxid1 = -1;

	for (int i = 1; i <= N; i++) {

		if (maxn1 < dist[i]) {

			maxn1 = dist[i];

			maxid1 = i;

		}

	}



	// Step #3. 頂点 maxid1 からの最短距離を求める

	// maxn2: 木の直径（最短距離の最大値）

	getdist(maxid1);

	int maxn2 = -1;

	for (int i = 1; i <= N; i++) {

		maxn2 = max(maxn2, dist[i]);

	}



	// Step #4. 出力

	cout << maxn2 + 1 << endl;

	return 0;

}

Crystal solution: class UnweightedGraph
  getter graph : Array(Array(Int32))

  def initialize(size : Int)
    @graph = Array.new(size) { Array(Int32).new }
  end

  def add_edge(v, u)
    @graph[v] << u
    @graph[u] << v
  end

  delegate size, to: @graph
  delegate :[], to: @graph

  private def tree_depth_dfs(v : Int32, p : Int32, dist : Int32, a : Array(Int32))
    a[v] = dist
    self[v].each do |u|
      tree_depth_dfs(u, v, dist + 1, a) if u != p
    end
  end

  def tree_depth(root : Int32)
    a = Array.new(size, 0)
    tree_depth_dfs(root, -1, 0, a)
    a
  end
end

n = read_line.to_i
graph = UnweightedGraph.new(n)
n.pred.times do
  a, b = read_line.split.map(&.to_i.pred)
  graph.add_edge(a, b)
end

_, v = graph.tree_depth(0).each_with_index.max
dist, _ = graph.tree_depth(v).each_with_index.max
puts dist + 1
AtCoder problem 003

C++ solution:
#include <iostream>

#include <vector>

#include <queue>

using namespace std;



// 入力

int N;

int A[1 << 18], B[1 << 18];



// グラフ

const int INF = (1 << 29);

vector<int> G[1 << 18];

int dist[1 << 18];



void getdist(int start) {

	// 幅優先探索（BFS）により、最短距離を計算

	for (int i = 1; i <= N; i++) dist[i] = INF;



	queue<int> Q;

	Q.push(start);

	dist[start] = 0;



	while (!Q.empty()) {

		int pos = Q.front(); Q.pop();

		for (int to : G[pos]) {

			if (dist[to] == INF) {

				dist[to] = dist[pos] + 1;

				Q.push(to);

			}

		}

	}

}



int main() {

	// Step #1. 入力

	cin >> N;

	for (int i = 1; i <= N - 1; i++) {

		cin >> A[i] >> B[i];

		G[A[i]].push_back(B[i]);

		G[B[i]].push_back(A[i]);

	}



	// Step #2. 頂点 1 からの最短距離を求める

	// maxid1: 頂点 1 から最も離れている（最短距離が長い）頂点

	getdist(1);

	int maxn1 = -1, maxid1 = -1;

	for (int i = 1; i <= N; i++) {

		if (maxn1 < dist[i]) {

			maxn1 = dist[i];

			maxid1 = i;

		}

	}



	// Step #3. 頂点 maxid1 からの最短距離を求める

	// maxn2: 木の直径（最短距離の最大値）

	getdist(maxid1);

	int maxn2 = -1;

	for (int i = 1; i <= N; i++) {

		maxn2 = max(maxn2, dist[i]);

	}



	// Step #4. 出力

	cout << maxn2 + 1 << endl;

	return 0;

}


Python solution: # でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
sys.setrecursionlimit(10**6)
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    G[a].append(b)
    G[b].append(a)

def dfs(s):
    D = [-1] * N
    D[s] = 0
    stk = [s]
    push, pop = stk.append, stk.pop
    while stk:
        v = pop()
        nd = D[v] + 1
        for nv in G[v]:
            if D[nv] >= 0: continue
            D[nv] = nd
            push(nv)
    return D

D0 = dfs(0)
mxi = max(enumerate(D0), key=lambda x: x[1])[0]
Dmx = dfs(mxi)
print(max(Dmx) + 1)
AtCoder problem 003

C++ solution:
#include <iostream>

#include <vector>

#include <queue>

using namespace std;



// 入力

int N;

int A[1 << 18], B[1 << 18];



// グラフ

const int INF = (1 << 29);

vector<int> G[1 << 18];

int dist[1 << 18];



void getdist(int start) {

	// 幅優先探索（BFS）により、最短距離を計算

	for (int i = 1; i <= N; i++) dist[i] = INF;



	queue<int> Q;

	Q.push(start);

	dist[start] = 0;



	while (!Q.empty()) {

		int pos = Q.front(); Q.pop();

		for (int to : G[pos]) {

			if (dist[to] == INF) {

				dist[to] = dist[pos] + 1;

				Q.push(to);

			}

		}

	}

}



int main() {

	// Step #1. 入力

	cin >> N;

	for (int i = 1; i <= N - 1; i++) {

		cin >> A[i] >> B[i];

		G[A[i]].push_back(B[i]);

		G[B[i]].push_back(A[i]);

	}



	// Step #2. 頂点 1 からの最短距離を求める

	// maxid1: 頂点 1 から最も離れている（最短距離が長い）頂点

	getdist(1);

	int maxn1 = -1, maxid1 = -1;

	for (int i = 1; i <= N; i++) {

		if (maxn1 < dist[i]) {

			maxn1 = dist[i];

			maxid1 = i;

		}

	}



	// Step #3. 頂点 maxid1 からの最短距離を求める

	// maxn2: 木の直径（最短距離の最大値）

	getdist(maxid1);

	int maxn2 = -1;

	for (int i = 1; i <= N; i++) {

		maxn2 = max(maxn2, dist[i]);

	}



	// Step #4. 出力

	cout << maxn2 + 1 << endl;

	return 0;

}






Ruby solution: def solve(graph, curr, prev)
    max_depth = 0
    max_score = 0

    for node in graph[curr]
        next if node == prev

        depth, score = solve(graph, node, curr)
        max_score = [max_score, score, depth + max_depth].max
        max_depth = [max_depth, depth].max
    end

    [max_depth + 1, max_score]
end

n = readline.to_i

graph = Array.new(n + 1) { [] }
(n - 1).times do
    a_i, b_i = readline.split.map(&:to_i)
    graph[a_i].push(b_i)
    graph[b_i].push(a_i)
end

puts solve(graph, 1, nil)[1] + 1
AtCoder problem 003

C++ solution:
#include <iostream>

#include <vector>

#include <queue>

using namespace std;



// 入力

int N;

int A[1 << 18], B[1 << 18];



// グラフ

const int INF = (1 << 29);

vector<int> G[1 << 18];

int dist[1 << 18];



void getdist(int start) {

	// 幅優先探索（BFS）により、最短距離を計算

	for (int i = 1; i <= N; i++) dist[i] = INF;



	queue<int> Q;

	Q.push(start);

	dist[start] = 0;



	while (!Q.empty()) {

		int pos = Q.front(); Q.pop();

		for (int to : G[pos]) {

			if (dist[to] == INF) {

				dist[to] = dist[pos] + 1;

				Q.push(to);

			}

		}

	}

}



int main() {

	// Step #1. 入力

	cin >> N;

	for (int i = 1; i <= N - 1; i++) {

		cin >> A[i] >> B[i];

		G[A[i]].push_back(B[i]);

		G[B[i]].push_back(A[i]);

	}



	// Step #2. 頂点 1 からの最短距離を求める

	// maxid1: 頂点 1 から最も離れている（最短距離が長い）頂点

	getdist(1);

	int maxn1 = -1, maxid1 = -1;

	for (int i = 1; i <= N; i++) {

		if (maxn1 < dist[i]) {

			maxn1 = dist[i];

			maxid1 = i;

		}

	}



	// Step #3. 頂点 maxid1 からの最短距離を求める

	// maxn2: 木の直径（最短距離の最大値）

	getdist(maxid1);

	int maxn2 = -1;

	for (int i = 1; i <= N; i++) {

		maxn2 = max(maxn2, dist[i]);

	}



	// Step #4. 出力

	cout << maxn2 + 1 << endl;

	return 0;

}




Rust solution: use proconio::{input,marker::Usize1};
use std::collections::VecDeque;

fn main(){
    input!{n:usize}
    let mut g=vec![vec![];n];
    for _ in 1..n{
        input!{x:Usize1,y:Usize1}
        g[x].push(y);
        g[y].push(x);
    }
    let mut d=vec![1<<30;n];
    bfs(&g,&mut d,0usize);
    let mut u:usize=0;
    let m=d.iter().max().unwrap();
    for i in 0..n{
        if &d[i]==m {u=i}
    }
    let mut d=vec![1<<30;n];
    bfs(&g,&mut d,u);
    println!("{}",1+d.iter().max().unwrap());
}

fn bfs(g:&Vec<Vec<usize>>,d:&mut Vec<isize>,s:usize){
    let mut q:VecDeque<usize>=VecDeque::new();
    d[s]=0;
    q.push_back(s);
    while q.len()>0{
        let i=q.pop_front().unwrap();
        for j in g[i].iter(){
            if d[*j]==1<<30{
                q.push_back(*j);
                d[*j]=d[i]+1;
            }
        }
    } 
}
AtCoder problem 003

C++ solution:
#include <iostream>

#include <vector>

#include <queue>

using namespace std;



// 入力

int N;

int A[1 << 18], B[1 << 18];



// グラフ

const int INF = (1 << 29);

vector<int> G[1 << 18];

int dist[1 << 18];



void getdist(int start) {

	// 幅優先探索（BFS）により、最短距離を計算

	for (int i = 1; i <= N; i++) dist[i] = INF;



	queue<int> Q;

	Q.push(start);

	dist[start] = 0;



	while (!Q.empty()) {

		int pos = Q.front(); Q.pop();

		for (int to : G[pos]) {

			if (dist[to] == INF) {

				dist[to] = dist[pos] + 1;

				Q.push(to);

			}

		}

	}

}



int main() {

	// Step #1. 入力

	cin >> N;

	for (int i = 1; i <= N - 1; i++) {

		cin >> A[i] >> B[i];

		G[A[i]].push_back(B[i]);

		G[B[i]].push_back(A[i]);

	}



	// Step #2. 頂点 1 からの最短距離を求める

	// maxid1: 頂点 1 から最も離れている（最短距離が長い）頂点

	getdist(1);

	int maxn1 = -1, maxid1 = -1;

	for (int i = 1; i <= N; i++) {

		if (maxn1 < dist[i]) {

			maxn1 = dist[i];

			maxid1 = i;

		}

	}



	// Step #3. 頂点 maxid1 からの最短距離を求める

	// maxn2: 木の直径（最短距離の最大値）

	getdist(maxid1);

	int maxn2 = -1;

	for (int i = 1; i <= N; i++) {

		maxn2 = max(maxn2, dist[i]);

	}



	// Step #4. 出力

	cout << maxn2 + 1 << endl;

	return 0;

}





Kuin solution: func main()
	var n: int :: cui@inputInt()
	var graph: []list<int> :: #[n]list<int>
	for i(0, n - 1)
		do graph[i] :: #list<int>
	end for
	for i(0, n - 2)
		var a: int :: cui@inputInt() - 1
		var b: int :: cui@inputInt() - 1
		do graph[a].add(b)
		do graph[b].add(a)
	end for
	
	var ans: int :: treeDiameter(graph) + 1
	do cui@print("\{ans}\n")
	
	func treeDiameter(graph: []list<int>): int
		var pos: int :: 0
		do treeDiameterSub(graph, &pos, -1)
		ret treeDiameterSub(graph, &pos, -1)
		
		func treeDiameterSub(graph: []list<int>, pos: &int, p: int): int
			var u: int :: pos
			var res: int :: 0
			do graph[u].head()
			while(!graph[u].term())
				var x: int :: graph[u].get()
				if(x <> p)
					var dist: int :: treeDiameterSub(graph, &x, u) + 1
					if(dist > res)
						do res :: dist
						do pos :: x
					end if
				end if
				do graph[u].next()
			end while
			ret res
		end func
	end func
end func
AtCoder problem 003

C++ solution:

Crystal solution: class UnweightedGraph
  getter graph : Array(Array(Int32))

  def initialize(size : Int)
    @graph = Array.new(size) { Array(Int32).new }
  end

  def add_edge(v, u)
    @graph[v] << u
    @graph[u] << v
  end

  delegate size, to: @graph
  delegate :[], to: @graph

  private def tree_depth_dfs(v : Int32, p : Int32, dist : Int32, a : Array(Int32))
    a[v] = dist
    self[v].each do |u|
      tree_depth_dfs(u, v, dist + 1, a) if u != p
    end
  end

  def tree_depth(root : Int32)
    a = Array.new(size, 0)
    tree_depth_dfs(root, -1, 0, a)
    a
  end
end

n = read_line.to_i
graph = UnweightedGraph.new(n)
n.pred.times do
  a, b = read_line.split.map(&.to_i.pred)
  graph.add_edge(a, b)
end

_, v = graph.tree_depth(0).each_with_index.max
dist, _ = graph.tree_depth(v).each_with_index.max
puts dist + 1


Python solution: # でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
sys.setrecursionlimit(10**6)
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    G[a].append(b)
    G[b].append(a)

def dfs(s):
    D = [-1] * N
    D[s] = 0
    stk = [s]
    push, pop = stk.append, stk.pop
    while stk:
        v = pop()
        nd = D[v] + 1
        for nv in G[v]:
            if D[nv] >= 0: continue
            D[nv] = nd
            push(nv)
    return D

D0 = dfs(0)
mxi = max(enumerate(D0), key=lambda x: x[1])[0]
Dmx = dfs(mxi)
print(max(Dmx) + 1)
AtCoder problem 003

C++ solution:

Crystal solution: class UnweightedGraph
  getter graph : Array(Array(Int32))

  def initialize(size : Int)
    @graph = Array.new(size) { Array(Int32).new }
  end

  def add_edge(v, u)
    @graph[v] << u
    @graph[u] << v
  end

  delegate size, to: @graph
  delegate :[], to: @graph

  private def tree_depth_dfs(v : Int32, p : Int32, dist : Int32, a : Array(Int32))
    a[v] = dist
    self[v].each do |u|
      tree_depth_dfs(u, v, dist + 1, a) if u != p
    end
  end

  def tree_depth(root : Int32)
    a = Array.new(size, 0)
    tree_depth_dfs(root, -1, 0, a)
    a
  end
end

n = read_line.to_i
graph = UnweightedGraph.new(n)
n.pred.times do
  a, b = read_line.split.map(&.to_i.pred)
  graph.add_edge(a, b)
end

_, v = graph.tree_depth(0).each_with_index.max
dist, _ = graph.tree_depth(v).each_with_index.max
puts dist + 1






Ruby solution: def solve(graph, curr, prev)
    max_depth = 0
    max_score = 0

    for node in graph[curr]
        next if node == prev

        depth, score = solve(graph, node, curr)
        max_score = [max_score, score, depth + max_depth].max
        max_depth = [max_depth, depth].max
    end

    [max_depth + 1, max_score]
end

n = readline.to_i

graph = Array.new(n + 1) { [] }
(n - 1).times do
    a_i, b_i = readline.split.map(&:to_i)
    graph[a_i].push(b_i)
    graph[b_i].push(a_i)
end

puts solve(graph, 1, nil)[1] + 1
AtCoder problem 003

C++ solution:

Crystal solution: class UnweightedGraph
  getter graph : Array(Array(Int32))

  def initialize(size : Int)
    @graph = Array.new(size) { Array(Int32).new }
  end

  def add_edge(v, u)
    @graph[v] << u
    @graph[u] << v
  end

  delegate size, to: @graph
  delegate :[], to: @graph

  private def tree_depth_dfs(v : Int32, p : Int32, dist : Int32, a : Array(Int32))
    a[v] = dist
    self[v].each do |u|
      tree_depth_dfs(u, v, dist + 1, a) if u != p
    end
  end

  def tree_depth(root : Int32)
    a = Array.new(size, 0)
    tree_depth_dfs(root, -1, 0, a)
    a
  end
end

n = read_line.to_i
graph = UnweightedGraph.new(n)
n.pred.times do
  a, b = read_line.split.map(&.to_i.pred)
  graph.add_edge(a, b)
end

_, v = graph.tree_depth(0).each_with_index.max
dist, _ = graph.tree_depth(v).each_with_index.max
puts dist + 1




Rust solution: use proconio::{input,marker::Usize1};
use std::collections::VecDeque;

fn main(){
    input!{n:usize}
    let mut g=vec![vec![];n];
    for _ in 1..n{
        input!{x:Usize1,y:Usize1}
        g[x].push(y);
        g[y].push(x);
    }
    let mut d=vec![1<<30;n];
    bfs(&g,&mut d,0usize);
    let mut u:usize=0;
    let m=d.iter().max().unwrap();
    for i in 0..n{
        if &d[i]==m {u=i}
    }
    let mut d=vec![1<<30;n];
    bfs(&g,&mut d,u);
    println!("{}",1+d.iter().max().unwrap());
}

fn bfs(g:&Vec<Vec<usize>>,d:&mut Vec<isize>,s:usize){
    let mut q:VecDeque<usize>=VecDeque::new();
    d[s]=0;
    q.push_back(s);
    while q.len()>0{
        let i=q.pop_front().unwrap();
        for j in g[i].iter(){
            if d[*j]==1<<30{
                q.push_back(*j);
                d[*j]=d[i]+1;
            }
        }
    } 
}