Problem: 2063C - Remove Exactly Two
Language: java

Solution 1 (runtime: 702 ms):
import javax.swing.tree.TreeNode;
import java.io.*;
import java.util.*;

/**
 * @Author: _Djhhh
 * @Introduction：
 */

public class Main {
    static FastReader fr = new FastReader();
    static FastWriter fw = new FastWriter();

    public static void solve() {
        int n=fr.nextInt();
        int[] in = new int[n];
        ArrayList<ArrayList<Integer>> to = new ArrayList<>();
        for(int i=0;i<n;i++){
            to.add(new ArrayList<>());
        }
        for(int i=0;i<n-1;i++){
            int x=fr.nextInt()-1;
            int y=fr.nextInt()-1;
            in[x]++;
            in[y]++;
            to.get(x).add(y);
            to.get(y).add(x);
        }
        int mx=0;
        int id1=0;
        for(int i=0;i<n;i++){
            if(in[i]>=mx){
                mx=in[i];
                int cnt=0;
                for(var y:to.get(i)){
                    if(in[y]==mx)cnt++;
                }
                if(cnt>=2)continue;
                id1=i;
            }
        }
        for(var y:to.get(id1)){
            in[y]--;
        }
        in[id1]=0;
        int mn=0;
        for(int i=0;i<n;i++){
            if(in[i]>=mn&&i!=id1){
                mn=in[i];
            }
        }
        fw.println((mx+mn-1));
    }

    public static void main(String[] args) {
        int t = 1;
        t = fr.nextInt();
        while (t-- > 0) solve();
    }
}

class DSU {
    int n;
    int[] fa;
    int[] dep;
    int[] siz;
    int[] edges;
    boolean[] v;
    DSU(int n) {
        fa = new int[n];
        dep = new int[n];
        siz = new int[n];
        edges = new int[n];
        v = new boolean[n];
        for (int i = 0; i < n; i++) {
            fa[i] = i;
            dep[i] = 0;
            siz[i] = 1;
            edges[i] = 0;
            v[i]=false;
        }
    }
    int look(int x) {
        if (fa[x] == x) return x;
        else return fa[x] = look(fa[x]);
    }
    void merge(int x, int y) {
        v[x]=v[y]=true;
        int xx = look(x);
        int yy = look(y);
        if (xx == yy) return;
        edges[xx] += edges[yy] + 1;
        siz[xx] += siz[yy];
        if (dep[xx] < dep[yy]) {
            fa[xx] = yy;
        } else {
            fa[yy] = xx;
        }

        if (dep[xx] == dep[yy]) dep[xx]++;
    }
    boolean isMerge(int x, int y) {
        return look(x) == look(y);
    }
    int getSize(int x) {
        return siz[look(x)];
    }
    int getEdges(int x) {
        return edges[look(x)];
    }
}
class Pair<T1, T2> {
    private T1 first;
    private T2 second;

    public Pair(T1 first, T2 second) {
        this.first = first;
        this.second = second;
    }
    public void setFirst(T1 first) {
        this.first=first;
    }

    public void setSecond(T2 second) {
        this.second=second;
    }
    public T1 getFirst() {
        return first;
    }

    public T2 getSecond() {
        return second;
    }
}
class Algorithm {
    /**
     * 查找第一个大于等于 x 的位置
     * @param arr 查找数组
     * @param x 值
     * @param L 左边界
     * @param R 右边界
     * @return 第一个大于等于 x 的位置
     */
    public static int lowBs(int[] arr, long x, int L, int R){
        int l = L;
        int r = R;
        int res = R + 1;
        while(l <= r){
            int mid = l+r>>1;
            if(arr[mid] >= x){
                res = mid;
                r = mid - 1;
            }
            else{
                l = mid + 1;
            }
        }
        return res;
    }

    /**
     * 查找第一个大于 x 的位置
     * @param arr 查找数组
     * @param x 值
     * @param L 左边界
     * @param R 右边界
     * @return 第一个大于 x 的位置
     */
    public static int highBs(int[] arr, long x, int L, int R) {
        int l = L;
        int r = R;
        int res = R + 1;
        while(l <= r){
            int mid = l+r>>1;
            if(arr[mid] > x){
                res = mid;
                r = mid -1;
            }
            else{
                l = mid +1;
            }
        }
        return res;
    }
}
class FastReader {
    BufferedReader br;
    StringTokenizer st;

    public FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    String nextLine() {
        String str = "";
        try {
            str = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    int[] nextIntArray() {
        String line = nextLine();
        String[] strNums = line.split("\\s+");
        int[] arr = new int[strNums.length];
        for (int i = 0; i < strNums.length; i++) {
            arr[i] = Integer.parseInt(strNums[i]);
        }
        return arr;
    }

    long[] nextLongArray() {
        String line = nextLine();
        String[] strNums = line.split("\\s+");
        long[] arr = new long[strNums.length];
        for (int i = 0; i < strNums.length; i++) {
            arr[i] = Long.parseLong(strNums[i]);
        }
        return arr;
    }

    char[] nextCharArray() {
        String line = nextLine();
        String[] strNums = line.split("\\s+");
        char[] arr = new char[strNums.length];
        for (int i = 0; i < strNums.length; i++) {
            arr[i] = strNums[i].charAt(0);
        }
        return arr;
    }

    char[] StringtoChar() {
        String line = nextLine();
        return line.toCharArray();
    }
}
class FastWriter {
    private final PrintWriter writer;

    public FastWriter() {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
    }

    public void print(Object object) {
        writer.print(object);
    }

    public void println(Object object) {
        writer.println(object);
    }

    public void flush() {
        writer.flush();
    }
}

Solution 2 (runtime: 1296 ms):
import java.io.*;
import java.util.*;

public class RemoveExactlyTwo {

    static int mod = 1000000007;

    public static void main(String[] args) throws IOException {

        FastReader reader = new FastReader();
        FastWriter writer = new FastWriter();

        int numTests = reader.readSingleInt();
        for (int t = 0; t < numTests; t++) {
            int n = reader.readSingleInt();

            Node[] nodes = new Node[n];
            for (int i = 0; i < n; i++) {
                nodes[i] = new Node(i);
            }

            for (int i = 0; i < n - 1; i++) {
                int[] uv = reader.readIntArray(2);
                int u = uv[0] - 1;
                int v = uv[1] - 1;
                nodes[u].children.add(nodes[v]);
                nodes[v].children.add(nodes[u]);
            }

            var largest = new HashSet<Node>();
            int max = 0;
            for (int i = 0; i < n; i++) {
                if (max == nodes[i].children.size()) {
                    largest.add(nodes[i]);
                } else if (max < nodes[i].children.size()) {
                    largest.clear();
                    largest.add(nodes[i]);
                    max = nodes[i].children.size();
                }
            }

            var toppers = new ArrayList<>(largest);
            var top = toppers.get(0);

            boolean allChildren = true;
            for (int i = 1; i < toppers.size(); i++) {
                if (!top.children.contains(toppers.get(i))) {
                    allChildren = false;
                    break;
                }
            }
            if (allChildren && toppers.size() > 1) {
                top = toppers.get(1);
            }


            for (var child : top.children) {
                child.children.remove(top);
            }
            top.children.clear();

            max = 0;
            for (int i = 0; i < n; i++) {
                if (nodes[max].children.size() < nodes[i].children.size()) {
                    max = i;
                }
            }

            for (var child : nodes[max].children) {
                child.children.remove(nodes[max]);
            }
            nodes[max].children.clear();

            var count = 0;
            var seen = new HashSet<Node>();
            for (int i = 0; i < n; i++) {
                if (seen.contains(nodes[i])) {
                    continue;
                }

                count++;

                seen.add(nodes[i]);
                var stack = new Stack<Node>();

                stack.push(nodes[i]);
                while (!stack.isEmpty()) {
                    top = stack.pop();
                    for (var child : top.children) {
                        if (seen.contains(child)) {
                            continue;
                        }
                        seen.add(child);
                        stack.push(child);
                    }
                }
            }

            writer.writeSingleInteger(count - 2);
        }
    }

    public static class Node {
        int id;
        Set<Node> children = new HashSet<>();

        Node(int id) {
            this.id = id;
        }
    }


    public static void mergeSort(int[] a, int n) {
        if (n < 2) {
            return;
        }
        int mid = n / 2;
        int[] l = new int[mid];
        int[] r = new int[n - mid];

        for (int i = 0; i < mid; i++) {
            l[i] = a[i];
        }
        for (int i = mid; i < n; i++) {
            r[i - mid] = a[i];
        }

        mergeSort(l, mid);
        mergeSort(r, n - mid);

        merge(a, l, r, mid, n - mid);
    }


    public static void merge(int[] a, int[] l, int[] r, int left, int right) {

        int i = 0, j = 0, k = 0;
        while (i < left && j < right) {
            if (l[i] <= r[j]) {
                a[k++] = l[i++];
            } else {
                a[k++] = r[j++];
            }
        }
        while (i < left) {
            a[k++] = l[i++];
        }
        while (j < right) {
            a[k++] = r[j++];
        }
    }


    public static class FastReader {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer;


        public int readSingleInt() throws IOException {
            return Integer.parseInt(reader.readLine());
        }

        public int[] readIntArray(int numInts) throws IOException {
            int[] nums = new int[numInts];
            tokenizer = new StringTokenizer(reader.readLine());
            for (int i = 0; i < numInts; i++) {
                nums[i] = Integer.parseInt(tokenizer.nextToken());
            }
            return nums;
        }

        public long[] readLongArray(int numInts) throws IOException {
            long[] nums = new long[numInts];
            tokenizer = new StringTokenizer(reader.readLine());
            for (int i = 0; i < numInts; i++) {
                nums[i] = Long.parseLong(tokenizer.nextToken());
            }
            return nums;
        }

        public String readString() throws IOException {
            return reader.readLine();
        }

    }


    public static class FastWriter {

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));


        public void writeSingleInteger(int i) throws IOException {
            writer.write(Integer.toString(i));
            writer.newLine();
            writer.flush();
        }

        public void writeSingleLong(long i) throws IOException {
            writer.write(Long.toString(i));
            writer.newLine();
            writer.flush();
        }

        public void writeIntArrayWithSpaces(int[] nums) throws IOException {
            for (int i = 0; i < nums.length; i++) {
                writer.write(nums[i] + " ");
            }
            writer.newLine();
            writer.flush();
        }

        public void writeLongArrayWithSpaces(long[] nums) throws IOException {
            for (int i = 0; i < nums.length; i++) {
                writer.write(nums[i] + " ");
            }
            writer.newLine();
            writer.flush();
        }

        public void writeIntArrayListWithSpaces(ArrayList<Integer> nums) throws IOException {
            for (int i = 0; i < nums.size(); i++) {
                writer.write(nums.get(i) + " ");
            }
            writer.newLine();
            writer.flush();
        }

        public void writeIntArrayWithoutSpaces(int[] nums) throws IOException {
            for (int i = 0; i < nums.length; i++) {
                writer.write(Integer.toString(nums[i]));
            }
            writer.newLine();
            writer.flush();
        }

        public void writeString(String s) throws IOException {
            writer.write(s);
            writer.newLine();
            writer.flush();
        }

    }


}