Problem: 2063C - Remove Exactly Two
Language: java

Solution 1 (runtime: 1093 ms):
  
/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {

    //------------------------------------------main--------------------------------------------------//
    public static void main(String[] args) throws java.lang.Exception {
        OutputStream outputStream = System.out;
        PrintWriter out = new PrintWriter(outputStream);
        FastReader sc = new FastReader();
        Task s = new Task(sc, out);
        s.solve();
        out.close();
        // your code goes here"
    }
}

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;
    }

    public int[] readIntArray(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = nextInt();
        }
        return arr;
    }

    public long[] readLongArray(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++) {
            arr[i] = nextLong();
        }
        return arr;
    }
}

class Task {

    PrintWriter out;
    FastReader sc;

    Task(FastReader sc, PrintWriter out) {
        this.sc = sc;
        this.out = out;
    }
    //----------------------------------------------inputfunction------------------------------------------//

    String st() {
        return sc.nextLine();
    }

    int i() {
        return sc.nextInt();
    }

    long l() {
        return sc.nextLong();
    }

    double d() {
        return sc.nextDouble();
    }

    //---------------------------------------------absolute----------------------------------------------//
    public long abs(long a) {
        return a < 0 ? -a : a;
    }

    public int abs(int a) {
        return a < 0 ? -a : a;
    }

    //-------------------------------------------max--------------------------------------------------//
    public int max(int a, int b) {
        return a >= b ? a : b;
    }

    public long max(long a, long b) {
        return a >= b ? a : b;
    }

    public int max(int a, int b, int c) {
        return Math.max(a, Math.max(b, c));
    }

    public long max(long a, long b, long c) {
        return Math.max(a, Math.max(b, c));
    }

    //------------------------------------------min---------------------------------------------------//
    public int min(int a, int b) {
        return a <= b ? a : b;
    }

    public long min(long a, long b) {
        return a <= b ? a : b;
    }

    public int min(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    public long min(long a, long b, long c) {
        return Math.min(a, Math.min(b, c));
    }

    //----------------------------------------sortingfunction---------------------------------------------//
    private void sort(int[] arr) {
        int n = arr.length;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(arr[i]);
        }
        Collections.sort(list);
        for (int i = 0; i < n; i++) {
            arr[i] = list.get(i);
        }
    }

    private void sort(char[] arr) {
        int n = arr.length;
        List<Character> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(arr[i]);
        }
        Collections.sort(list);
        for (int i = 0; i < n; i++) {
            arr[i] = list.get(i);
        }
    }

    private void rsort(char[] arr) {
        int n = arr.length;
        List<Character> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(arr[i]);
        }
        Collections.sort(list, Collections.reverseOrder());
        for (int i = 0; i < n; i++) {
            arr[i] = list.get(i);
        }
    }

    private void rsort(int[] arr) {
        int n = arr.length;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(arr[i]);
        }
        Collections.sort(list, Collections.reverseOrder());
        for (int i = 0; i < n; i++) {
            arr[i] = list.get(i);
        }
    }

    private void sort(long[] arr) {
        int n = arr.length;
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(arr[i]);
        }
        Collections.sort(list);
        for (int i = 0; i < n; i++) {
            arr[i] = list.get(i);
        }
    }

    private void rsort(long[] arr) {
        int n = arr.length;
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(arr[i]);
        }
        Collections.sort(list, Collections.reverseOrder());
        for (int i = 0; i < n; i++) {
            arr[i] = list.get(i);
        }
    }
    //---------------------------------------power----------------------------------------------------//

    public long pow(long a, int b) {
        long ans = 1L;
        while (b > 0) {
            if ((b & 1) > 0) {
                ans *= a;
            }
            a *= a;
            b >>= 1;
        }
        return b;
    }
    //----------------------------------------binary_exponentiation-----------------------------------//

    public long exp(long a, long b, long mod) {
        long ans = 1L;
        while (b > 0) {
            if ((b & 1) > 0) {
                ans = (ans * a) % mod;
            }
            a = (a * a) % mod;
            b >>= 1;
        }
        return ans;
    }
    int t;
    public void solve() throws IOException {
        t = sc.nextInt();
        while (t-- > 0) {
            int n = i();
            List<Set<Integer>> a = new ArrayList<>();
            int[][] in = new int[n+1][2];
            for(int i =0;i<=n;i++){
                a.add(new HashSet<>());
                in[i][1] = i;
            }
            for(int i = 1;i<n;i++){
                int x = i(), y = i();
                a.get(x).add(y);
                a.get(y).add(x);
                in[x][0]++; in[y][0]++;
            }
            Arrays.sort(in, (x, y) -> y[0] - x[0]);
            int ans = 0;
            for(int i = 1;i<=n;i++){
                for(int e: a.get(i)){
                    ans = max(ans, a.get(i).size() + a.get(e).size() - 2);
                }
            }
            for(int i = 0;i<n;i++){
                for(int j = i+1;j<n;j++){
                    if(a.get(in[i][1]).contains(in[j][1])) continue;
                    ans = max(ans, in[i][0] + in[j][0] - 1);
                    break;
                }
            }
            out.print(ans);
            out.print("\n");
        }
    }
}


Solution 2 (runtime: 796 ms):

import java.io.*;
import java.util.*;

public class CodeForces {
    public static final int MOD = 1_000_000_007;
    public static final int BUFFERSIZE = 512000;
    //    private static Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in), BUFFERSIZE));
    private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out, BUFFERSIZE));


    static class Pair<T, E> {
        private T first;
        private E second;

        public Pair(T key, E value) {
            this.first = key;
            this.second = value;
        }

    }

    public static int solve(int n, ArrayList<Integer> connections[]) throws Exception {
        for (int k = 0; k < 2; k++) {
            int maxConnections = Integer.MIN_VALUE;
            int maxVertex = -1;
            for (int i = 1; i <= n; i++) {
                if (connections[i] != null && connections[i].size() > maxConnections) {
                    maxVertex = i;
                    maxConnections = connections[i].size();
                }else{
                    if (connections[i] != null && connections[i].size() == maxConnections) {
                        boolean take = false;
                        for (int j = 0; j < connections[i].size(); j++) {
                            int connectedTo = connections[i].get(j);  // 1 5
                            for (int l = 0; l < connections[connectedTo].size(); l++) {
                                if(connections[connectedTo].get(l) == i) continue;
                                if(connections[connections[connectedTo].get(l)].size() >= maxConnections){
                                    take = true;
                                    maxVertex = i;
                                    break;
                                }
                            }
                            if(take){
                                break;
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < connections[maxVertex].size(); i++) {
                int toRemove = connections[maxVertex].get(i);
                connections[toRemove].remove((Object) maxVertex);
            }
            connections[maxVertex]  = null;
        }
        int ans = 0;
        boolean marked[] = new boolean[n + 1];
        for (int i = 1; i <= n ; i++) {
            if(!marked[i] && connections[i] != null){
                dfs(connections, i, marked);
                ans++;
            }
        }
        return ans;
    }

    private static void dfs(ArrayList<Integer>[] connections, int vertex, boolean[] marked) {
        if(marked[vertex])
            return;
        marked[vertex] = true;
        for (int connectedVertex :connections[vertex]) {
            dfs(connections, connectedVertex, marked);
        }
    }


    public static void main(String args[]) throws Exception {
        in.init(System.in);
        Random random = new Random();
//        int totalTestCases = 10000;
        int totalTestCases = in.nextInt();
        for (int testCase = 0; testCase < totalTestCases; testCase++) {
            int n = in.nextInt();
            ArrayList<Integer> connections[] = new ArrayList[n + 1];
            for (int i = 1; i <= n; i++) {
                connections[i] = new ArrayList<>();
            }
            for (int i = 0; i < n - 1; i++) {
                int a = in.nextInt();
                int b = in.nextInt();
                connections[a].add(b);
                connections[b].add(a);
            }
            out.println(solve(n, connections));
//            long s2 = solve2(n, k, a, b);
//            if(s1 != s2){
//                System.out.println(n + " " + k);
//                System.out.println(Arrays.toString(a));
//                System.out.println(Arrays.toString(b));
//            }
//            long t2 = System.currentTimeMillis();
//            String solve2 = solve2(a);
//            long t3 = System.currentTimeMillis();
//            System.out.println(t3-t2);
//            System.out.println(t2-t1);
//            if(!solve1.equals(solve2)){
//                System.out.println(Arrays.toString(a));
//                System.out.println(solve1);
//                System.out.println(solve2);
//            }
        }
        out.close();
    }


    private static int lowerBound(int[] ar, int i) {
        int start = 0;
        int end = ar.length - 1;
        // 5, 7, 9
        int candidate = ar.length;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (ar[mid] >= i) {
                candidate = mid;
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return candidate;
    }

//    public static void numberPrimeNumber() {
//        int nn = 12;
//        int arr[] = new int[nn + 1];
//        for (int i = 1; i <= nn; ++i) {
//            for (int j = 2 * i; j <= nn; j += i) {
//                if (arr[j] == arr[i]) {
//                    ++arr[j];
//                }
//            }
//        }
//    }


    public static List<Integer> calculatePrimes(int n) {
        List<Integer> primes = new ArrayList<>();

        boolean[] isPrime = new boolean[n + 1];

        for (int i = 2; i <= n; i++) {
            isPrime[i] = true;
        }

        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = false;
                }
            }
        }

        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
        }

        return primes;
    }

    public static class in {
        static BufferedReader reader;
        static StringTokenizer tokenizer;

        static void init(InputStream input) {
            reader = new BufferedReader(new InputStreamReader(input), BUFFERSIZE);
            tokenizer = new StringTokenizer("");
        }

        static String next() throws IOException {
            while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
            return tokenizer.nextToken();
        }

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

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

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

    static {
        Bigmod.reset(false, 300300);
    }

    static class Bigmod {
        static long M9 = 998244353L, M1 = 1000_000_007L;
        static long M = 0;
        static int MAXN = -1;
        static long[] cacheStepmul;
        static long[] cacheStepmulInv;
        static long[] exp2;
        long num = 0;

        // TODO: reset this before anything.
        static void reset(boolean use998, int maxN) {
            // 300300
            M = use998 ? M9 : M1;
            MAXN = maxN;
            cacheStepmul = new long[MAXN];
            cacheStepmulInv = new long[MAXN];
            exp2 = new long[MAXN];
        }

        Bigmod(long num) {
            if (num >= 0) {
                this.num = num % M;
            } else {
                this.num = M - (-num) % M;
            }
        }

        static Bigmod valueOf(long num) {
            return new Bigmod(num);
        }

        @Override
        public String toString() {
            return Long.toString(num);
        }

        Bigmod add(long x) {
            if (x > 0) {
                num = (num + x % M) % M;
            } else if (x < 0) {
                num = (num - (-x) % M + M) % M;
            }
            return this;
        }

        Bigmod add(Bigmod bm) {
            return add(bm.num);
        }

        Bigmod sub(long x) {
            return add(-x);
        }

        Bigmod sub(Bigmod bm) {
            return add(-bm.num);
        }

        Bigmod mul(long x) {
            num = num * (x % M) % M;
            return this;
        }

        Bigmod mul(Bigmod bm) {
            return mul(bm.num);
        }

        Bigmod div(long x) {
            if (x == 0) throw new RuntimeException("cannot div 0.");
            return mul(exp(x, M - 2));
        }

        Bigmod div(Bigmod bm) {
            return div(bm.num);
        }

        Bigmod exp(long p) {
            long ret = 1L, baseLong = num % M;
            for (int i = 0; i <= 60 && p > 0; ++i) { //1<<30=1073741824
                if ((p & (1L << i)) > 0) {
                    ret = ret * baseLong % M;
                    p ^= (1L << i);
                }
                baseLong = baseLong * baseLong % M;
            }
            if (p != 0) throw new RuntimeException("p should reduced to 0 in exp.");
            num = ret;
            return this;
        }

        Bigmod exp(Bigmod bm) {
            return exp(bm.num);
        }

        static long exp(long x, long p) {
            return new Bigmod(x).exp(p).num;
        }

        static long exp2(long n) { // 2^n
            if (n >= exp2.length) throw new RuntimeException("overflow exp2 size. " + n + " >= " + exp2.length);
            if (exp2[0] == 0) {
                exp2[0] = 1;
                for (int i = 1; i < exp2.length; ++i)
                    exp2[i] = exp2[i - 1] * 2 % M;
            }
            return exp2[(int) n];
        }

        static long C(long n, long m) {
            if (n < 0 || m < 0) throw new RuntimeException("n/m cannot be negative in C(n,m).");
            if (n < m) throw new RuntimeException("n is less than m in C(n,m).");
            if (n == 0) return 1;
            if (m == 0 || m == n) return 1;
            return new Bigmod(P(n, m)).mul(stepmulInv(m)).num;
        }

        static long P(long n, long m) {
            if (n < 0 || m < 0) throw new RuntimeException("n/m cannot be negative in P(n,m).");
            if (n < m) throw new RuntimeException("n is less than m in P(n,m).");
            if (n == 0) return 1;
            if (n < cacheStepmul.length) {
                // P(n,m)=n!/(n-m)!
                return new Bigmod(stepmul(n)).mul(stepmulInv(n - m)).num;
            }
            // NOTE: O(m) complexity when n is large.
            Bigmod r = new Bigmod(1);
            long val = n;
            for (long i = 0; i < m; ++i) r.mul(val--);
            return r.num;
        }

        static long stepmul(long n) { // n!
            if (n >= cacheStepmul.length) throw new RuntimeException("overflow cacheSm size.");
            if (cacheStepmul[0] == 0) {
                cacheStepmul[0] = 1;
                cacheStepmulInv[0] = exp(cacheStepmul[0], M - 2);
                for (int i = 1; i < cacheStepmul.length; ++i) {
                    cacheStepmul[i] = cacheStepmul[i - 1] * i % M;
                    cacheStepmulInv[i] = exp(cacheStepmul[i], M - 2);
                }
            }
            return cacheStepmul[(int) n];
        }

        static long stepmulInv(long n) {
            if (cacheStepmulInv[1] == 0) stepmul(2);
            return cacheStepmulInv[(int) n];
        }


    }
}