Explanation
Let's focus on one tree and its diameter first, naming the two endpoints and . For every vertex on this tree, is either equal to or , which we can show as proved here.
Additionally, even if the tree has multiple diameters, only the points with the lowest ID are taken, still resulting in two unique points showing up for each tree.
So, we can count the number of distinct vertices in and divide by two to find the number of trees, being careful to count the case where = as one tree, since it is just an isolated vertex to be counted as one tree.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int n;cin >> n;// Array storing whether vertices have been visitedvector<bool> visited(n);int ans = 0;for (int i = 0; i < n; i++) {
Python
n = int(input())nums = list(map(int, input().split()))# Array storing whether vertices have been visitedvisited = [False] * nans = 0for i in range(n):if i + 1 == nums[i]:ans += 2elif not visited[nums[i] - 1]:ans += 1visited[nums[i] - 1] = Trueprint(ans // 2)
Java
import java.io.*;import java.util.StringTokenizer;public class Main {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new InputStreamReader(System.in));PrintWriter pw = new PrintWriter(System.out);int n = Integer.parseInt(r.readLine());// Array storing whether vertices have been visited
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!