題目連結: https://zerojudge.tw/ShowProblem?problemid=b967

# 程式碼

#include<bits/stdc++.h>
#define MAX 100001
using namespace std;
vector <int> F[MAX];
int md;
int DFS(int x) {
	int max1, max2, result;
	if (F[x].size() == 0) return 0;
	if (F[x].size() == 1) return DFS(F[x][0])+1;
	else {
		for (int i = 0; i<F[x].size(); i++) {
			result = DFS(F[x][i]) + 1;
			if (i == 0) max1 = result;
			else if (i == 1) {
				if (max1 >= result) max2 = result;
				else {
					max2 = max1;
					max1 = result;
				}
			} else {
				if (max1 <= result) {
					max2 = max1;
					max1 = result;
				}
				else if (max2 < result) max2 = result;
			}
		}
		md = max(md, max1 + max2);
            return max1;
	}
}
int main() {
	int a, b,root,rd,n;
	bool isChild[MAX];
	while (scanf("%d", &n) != EOF) {
		md = 0;
		for (int i = 0; i<n; i++) {
			F[i].clear();
			isChild[i] = false;
		}
		for (int i = 1; i<n; i++) {
			scanf("%d %d", &a, &b);
			F[a].push_back(b);
			isChild[b] = true;
		}
		for (int i = 0; i < n; i++) {
			if (!isChild[i]) {
				root = i;
				break;
			}
		}
		rd = DFS(root);
	    md = max(rd,md);
		printf("%d\n", md);
	}
}
更新於 閱讀次數

用實際行動犒賞爆肝的我😀

Zrn Ye LinePay

LinePay