// Problem: C. Remove Exactly Two
// Contest: Codeforces - Codeforces Round 1000 (Div. 2)
// URL: https://codeforces.com/contest/2063/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// by znzryb
//
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define ROF(i, a, b) for (int i = (a); i >= (b); --i)
#define all(x) x.begin(), x.end()
#define CLR(i, a) memset(i, a, sizeof(i))
#define fi first
#define se second
#define pb push_back
#define SZ(a) ((int)a.size())
#define LOCAL

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
typedef array<ll, 3> arr;
typedef double DB;
typedef pair<DB, DB> pdd;
constexpr ll MAXN = static_cast<ll>(2e5) + 10, INF = static_cast<ll>(5e18) + 3;

ll N, M, T;
vector<ll> g[MAXN];
ll edges[MAXN];

inline void solve() {
  cin >> N;
  map<ll, ll> cnt;
  // 初始化
  FOR(i, 1, N) { g[i].clear(); }
  FOR(i, 1, N - 1) {
    ll u, v;
    cin >> u >> v;
    g[u].pb(v);
    g[v].pb(u);
  }
  if (N == 2) {
    cout << 0 << '\n';
    return;
  }
  ll mx = 0, mxN = 1;
  FOR(i, 1, N) {
    edges[i] = SZ(g[i]);
    cnt[edges[i]] = cnt.find(edges[i]) == cnt.end() ? 1 : cnt[edges[i]] + 1;
  }
  ll ans = 0;
  map<ll, ll> backup = cnt;
  FOR(i, 1, N) {
    ll lans = edges[i];
// #ifdef LOCAL
    // cerr << i << ' ' << edges[i] << '\n';
// #endif
    cnt[edges[i]] -= 1;
    if (cnt[edges[i]] == 0) {
      cnt.erase(edges[i]);
    }
    FOR(j, 0, SZ(g[i]) - 1) {
      ll node = g[i][j];
      cnt[edges[node]] -= 1;
      cnt[edges[node] - 1] = cnt.find(edges[node] - 1) == cnt.end() ? 1 : cnt[edges[node] - 1] + 1;
      if (cnt[edges[node]] == 0) {
        cnt.erase(edges[node]);
      }
    }
    lans -= 1;  // 先不管我们这个要做第二个操作的联通块
    if (cnt.rbegin()->fi > 1) {
      // #ifdef LOCAL
      // cerr << lans << '\n';
      // #endif
      lans += cnt.rbegin()->se;
    } else if (cnt.rbegin()->fi == 1) {
      lans += cnt.rbegin()->se - 1;
    }

// #ifdef LOCAL
    // cerr << i << ' ' << lans << '\n';
// #endif
    ans = max(ans, lans);
    cnt = backup;
  }
  cout << ans << '\n';
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> T;
  while (T--) {
    solve();
#ifdef LOCAL
    cerr << '\n';
#endif
  }
  return 0;
}
/*

*/

// Problem: C. Remove Exactly Two
// Contest: Codeforces - Codeforces Round 1000 (Div. 2)
// URL: https://codeforces.com/contest/2063/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// by znzryb
//
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define ROF(i, a, b) for (int i = (a); i >= (b); --i)
#define all(x) x.begin(), x.end()
#define CLR(i, a) memset(i, a, sizeof(i))
#define fi first
#define se second
#define pb push_back
#define SZ(a) ((int)a.size())
#define LOCAL

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
typedef array<ll, 3> arr;
typedef double DB;
typedef pair<DB, DB> pdd;
constexpr ll MAXN = static_cast<ll>(2e5) + 10, INF = static_cast<ll>(5e18) + 3;

ll N, M, T;
vector<ll> g[MAXN];
ll edges[MAXN];

inline void solve() {
  cin >> N;
  map<ll, ll> cnt;
  // 初始化
  FOR(i, 1, N) { g[i].clear(); }
  FOR(i, 1, N - 1) {
    ll u, v;
    cin >> u >> v;
    g[u].pb(v);
    g[v].pb(u);
  }
  if (N == 2) {
    cout << 0 << '\n';
    return;
  }
  ll mx = 0, mxN = 1;
  FOR(i, 1, N) {
    edges[i] = SZ(g[i]);
    cnt[edges[i]] = cnt.find(edges[i]) == cnt.end() ? 1 : cnt[edges[i]] + 1;
  }
  ll ans = 0;
  map<ll, ll> backup = cnt;
  FOR(i, 1, N) {
    ll lans = edges[i];
    // #ifdef LOCAL
    // cerr << i << ' ' << edges[i] << '\n';
    // #endif
    cnt[edges[i]] -= 1;
    if (cnt[edges[i]] == 0) {
      cnt.erase(edges[i]);
    }
    FOR(j, 0, SZ(g[i]) - 1) {
      ll node = g[i][j];
      cnt[edges[node]] -= 1;
      cnt[edges[node] - 1] = cnt.find(edges[node] - 1) == cnt.end() ? 1 : cnt[edges[node] - 1] + 1;
      if (cnt[edges[node]] == 0) {
        cnt.erase(edges[node]);
      }
    }
    lans -= 1;  // 先不管我们这个要做第二个操作的联通块
    if (cnt.rbegin()->fi > 1) {
      // #ifdef LOCAL
      // cerr << lans << '\n';
      // #endif
      lans += cnt.rbegin()->fi;
    } else if (cnt.rbegin()->fi == 1) {
      // #ifdef LOCAL
      // cerr<<"In if:" << i << ' ' << lans << '\n';
      // #endif
      lans += cnt.rbegin()->fi - 1;
    }

    // #ifdef LOCAL
    // cerr << i << ' ' << lans << '\n';
    // #endif
    ans = max(ans, lans);
    cnt = backup;
  }
  cout << ans << '\n';
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> T;
  while (T--) {
    solve();
#ifdef LOCAL
    cerr << '\n';
#endif
  }
  return 0;
}
/*

*/

Answer: 2


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

void solve(){
	int n;cin>>n;
	vector<vector<int>> adj(n+1);
	vector<int> edges(n+1);
	for(int i=0; i<n-1; i++){
		int a,b;cin>>a>>b;
		adj[a].push_back(b);
		adj[b].push_back(a);
		edges[a]++;
		edges[b]++;
	}
	if(n==2){
		cout<<0<<endl;
		return ;
	}
	long long max = -1,node=-1;;
	for(int i=1; i<=n; i++){
		if(edges[i] > max){
			node = i;
			max = edges[i];
		}
	}
	bool flag = false;
	for(auto it: adj[node]){
		if(edges[it] == max){

			if(flag){
			cout<<max*2-1<<endl;
			return ;}flag = true;
		}
		edges[it]--;
	}
	long long max2=-1,node2=-1;
	for(int i=1; i<=n; i++){
		if(edges[i]>max2 && i != node){
			node2=i;
			max2=edges[i];
		}
	}
	cout<<max+max2-1<<endl;
}

int main(){
	int t;cin>>t;
	while(t--){
		solve();
	}
}

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

void solve(){
	int n;cin>>n;
	vector<vector<int>> adj(n+1);
	vector<int> edges(n+1);
	for(int i=0; i<n-1; i++){
		int a,b;cin>>a>>b;
		adj[a].push_back(b);
		adj[b].push_back(a);
		edges[a]++;
		edges[b]++;
	}
	if(n==2){
		cout<<0<<endl;
		return ;
	}
	long long max = -1,node=-1;;
	for(int i=1; i<=n; i++){
		if(edges[i] > max){
			node = i;
			max = edges[i];
		}
	}
	for(auto it: adj[node]){
		edges[it]--;
	}

	long long max2=-1,node2=-1;
	for(int i=1; i<=n; i++){
		if(edges[i]>max2 && i != node){
			node2=i;
			max2=edges[i];
		}
	}
	cout<<max+max2-1<<endl;
}

int main(){
	int t;cin>>t;
	while(t--){
		solve();
	}
}

Answer: 1


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

public class sub {

	static int mod = 998244353;

	public static void main(String args[]) throws IOException {
		int t = sc.nextInt();
		while(t-->0) {
			int n = sc.nextInt();
			ArrayList<ArrayList<Integer>> adj = new ArrayList();
			for(int i = 0;i<n;i++)adj.add(new ArrayList());
			int deg[] = new int[n];
			for(int i = 0;i<n-1;i++) {
				int u = sc.nextInt()-1;
				int v = sc.nextInt()-1;
				adj.get(u).add(v);
				adj.get(v).add(u);
				deg[u]++;
				deg[v]++;
			}
			PriorityQueue<Integer> pq = new PriorityQueue(Collections.reverseOrder());
			for(int i = 0;i<deg.length;i++) {
				pq.add(deg[i]);
			}
			int ans = 0;
			for(int i = 0;i<n;i++) {
				for(int j : adj.get(i)) {
					ans = Math.max(ans, deg[j]+deg[i]-2);
					pq.remove(deg[j]);
				}
				pq.remove(deg[i]);
				//out.println(pq);
				ans=Math.max(deg[i]+(pq.peek()==null?0:pq.peek())-1, ans);
				for(int j : adj.get(i)) {
					pq.add(deg[j]);
				}
				pq.add(deg[i]);
			}
			out.println(ans);
		}
		out.close();
	}

//	static long bincoef(int n, int k) {
//	    if (n < k) return 0L;
//	    return (p[n] * pow((p[n - k] * p[k]) % mod, mod - 2, mod)) % mod;
//	}

	static class Node implements Comparable<Node> {
        long cost;
        int u, v;
        Node(long cost, int u, int v) {
            this.cost = cost;
            this.u = u;
            this.v = v;
        }
        public int compareTo(Node o) {
            return Long.compare(this.cost, o.cost);
        }
    }

	static long pow(long a, long b, long mod) {
		if (b == 0) {
			return 1L;
		}
		long val = pow(a, b / 2, mod);
		if (b % 2 == 0) {
			return val * val % mod;
		}
		return val * val % mod * a % mod;
	}

	static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	static long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	static Kattio sc = new Kattio();
	static PrintWriter out = new PrintWriter(System.out);

	static class Kattio {

		static BufferedReader r;
		static StringTokenizer st;

		public Kattio() {
			r = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() {
			try {
				while (st == null || !st.hasMoreTokens()) {
					st = new StringTokenizer(r.readLine());
				}
				return st.nextToken();
			} catch (Exception e) {
				return null;
			}
		}

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

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

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

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

public class sub {

	static int mod = 998244353;

	public static void main(String args[]) throws IOException {
		int t = sc.nextInt();
		while(t-->0) {
			int n = sc.nextInt();
			ArrayList<ArrayList<Integer>> adj = new ArrayList();
			for(int i = 0;i<n;i++)adj.add(new ArrayList());
			int deg[] = new int[n];
			for(int i = 0;i<n-1;i++) {
				int u = sc.nextInt()-1;
				int v = sc.nextInt()-1;
				adj.get(u).add(v);
				adj.get(v).add(u);
				deg[u]++;
				deg[v]++;
			}
			TreeMap<Integer, Integer> tm = new TreeMap(Collections.reverseOrder());
			for(int i = 0;i<deg.length;i++) {
				tm.put(deg[i], tm.getOrDefault(deg[i], 0)+1);
			}
			int ans = 0;
			for(int i = 0;i<n;i++) {
				for(int j : adj.get(i)) {
					ans = Math.max(ans, deg[j]+deg[i]-2);
					tm.put(deg[j], tm.get(deg[j])-1);
					if(tm.get(deg[j])==0) {
						tm.remove(deg[j]);
					}
				}
				tm.put(deg[i], tm.get(deg[i])-1);
				if(tm.get(deg[i])==0) {
					tm.remove(deg[i]);
				}
				//out.println(pq);
				ans=Math.max(ans, deg[i]+(tm.isEmpty() ? 0: tm.firstKey())-1);
				for(int j : adj.get(i)) {
					tm.put(deg[j], tm.getOrDefault(deg[j], 0)+1);
				}
				tm.put(deg[i], tm.getOrDefault(deg[i],0)+1);
			}
			out.println(ans);
		}
		out.close();
	}

//	static long bincoef(int n, int k) {
//	    if (n < k) return 0L;
//	    return (p[n] * pow((p[n - k] * p[k]) % mod, mod - 2, mod)) % mod;
//	}

	static long pow(long a, long b, long mod) {
		if (b == 0) {
			return 1L;
		}
		long val = pow(a, b / 2, mod);
		if (b % 2 == 0) {
			return val * val % mod;
		}
		return val * val % mod * a % mod;
	}

	static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	static long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	static Kattio sc = new Kattio();
	static PrintWriter out = new PrintWriter(System.out);

	static class Kattio {

		static BufferedReader r;
		static StringTokenizer st;

		public Kattio() {
			r = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() {
			try {
				while (st == null || !st.hasMoreTokens()) {
					st = new StringTokenizer(r.readLine());
				}
				return st.nextToken();
			} catch (Exception e) {
				return null;
			}
		}

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

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

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

Answer: 2


#include <chrono>
#include <iostream>
#include <random>

#include <algorithm>

#include <map>
#include <set>

#ifdef GRINDSET
#include "../debug.h"
#else
#define debug(...) ;
#define print(...) ;
#endif

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
typedef vector<vector<vector<ll>>> vvvll;

template <typename T>
concept iterable =
    requires(T a) {
        { std::begin(a) } -> std::input_iterator;
        { std::end(a) } -> std::sentinel_for<decltype(std::begin(a))>;
    } &&
    !std::convertible_to<T, std::string>;

template<class T>
requires iterable<T>
std::ostream& operator<<(std::ostream& out, const T& a);

template<class T, class S>
std::ostream& operator<<(std::ostream& out, const std::pair<T, S>& a);

template<class T>
requires iterable<T>
std::istream& operator>>(std::istream& in, T& a);

template<class T, class S>
std::istream& operator>>(std::istream& in, std::pair<T, S>& a);

template<class T>
requires iterable<T>
std::ostream& operator<<(std::ostream& out, const T& a) {
    for (auto& e : a) {
        out << e << " ";
    }
    out << "\n";
    return out;
}

template<class T, class S>
std::ostream& operator<<(std::ostream& out, const std::pair<T, S>& a) {
    out << a.first << ": " << a.second << "\n";
    return out;
}

template<class T>
requires iterable<T>
std::istream& operator>>(std::istream& in, T& a) {
    for (auto& e : a) {
        in >> e;
    }
    return in;
}

template<class T, class S>
std::istream& operator>>(std::istream& in, std::pair<T, S>& a) {
    in >> a.first >> a.second;
    return in;
}

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int kMaxN = 2e5 + 5;
vi g[kMaxN];
int snd[kMaxN];
int low[kMaxN];

void DFS(int v, int p = 0) {
    low[v] = -1;
    int max_low = -1;
    int max_deg = 0;
    for (int u : g[v]) {
        if (u != p) {
            DFS(u, v);
            max_low = max(max_low, low[u]);
            low[v] = max({low[v], low[u]});
            if (g[u].size() > 1) {
                low[v] = max(low[v], (int)g[u].size());
            }
            max_deg = max(max_deg, (int)g[u].size());
        }
    }
    debug(v, snd[v]);
    if (g[v].size() > 1 || !p) {
        snd[v] = max((int)g[v].size() + max_low - 1, (int)(g[v].size()) - 2 + max_deg);
    } else {
        snd[v] = 0;
    }
    debug(snd[v], max_low, low[v]);
}

void Solve() {
    int n;
    cin >> n;

    for (int i = 1; i <= n; ++i) {
        g[i].clear();
    }

    for (int i = 1; i < n; ++i) {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }

    DFS(1);
    // for (int i = 1; i <= n; ++i) {
    //     cout << snd[i] << " ";
    // }
    // cout << "\n";
    cout << *std::max_element(snd + 1, snd + 1 + n) << "\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t;
    cin >> t;

    while (t--) {
        Solve();
    }
}

#include <chrono>
#include <iostream>
#include <random>

#include <algorithm>

#include <map>
#include <set>

#ifdef GRINDSET
#include "../debug.h"
#else
#define debug(...) ;
#define print(...) ;
#endif

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
typedef vector<vector<vector<ll>>> vvvll;

template <typename T>
concept iterable =
    requires(T a) {
        { std::begin(a) } -> std::input_iterator;
        { std::end(a) } -> std::sentinel_for<decltype(std::begin(a))>;
    } &&
    !std::convertible_to<T, std::string>;

template<class T>
requires iterable<T>
std::ostream& operator<<(std::ostream& out, const T& a);

template<class T, class S>
std::ostream& operator<<(std::ostream& out, const std::pair<T, S>& a);

template<class T>
requires iterable<T>
std::istream& operator>>(std::istream& in, T& a);

template<class T, class S>
std::istream& operator>>(std::istream& in, std::pair<T, S>& a);

template<class T>
requires iterable<T>
std::ostream& operator<<(std::ostream& out, const T& a) {
    for (auto& e : a) {
        out << e << " ";
    }
    out << "\n";
    return out;
}

template<class T, class S>
std::ostream& operator<<(std::ostream& out, const std::pair<T, S>& a) {
    out << a.first << ": " << a.second << "\n";
    return out;
}

template<class T>
requires iterable<T>
std::istream& operator>>(std::istream& in, T& a) {
    for (auto& e : a) {
        in >> e;
    }
    return in;
}

template<class T, class S>
std::istream& operator>>(std::istream& in, std::pair<T, S>& a) {
    in >> a.first >> a.second;
    return in;
}

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int kMaxN = 2e5 + 5;
vi g[kMaxN];
int par[kMaxN];

void DFS(int v, int p = 0) {
    par[v] = p;
    for (int u : g[v]) {
        if (u != p) {
            DFS(u, v);
        }
    }
}

void Solve() {
    int n;
    cin >> n;

    for (int i = 1; i <= n; ++i) {
        g[i].clear();
    }

    for (int i = 1; i < n; ++i) {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }

    vi ord(n + 1);
    iota(ord.begin(), ord.end(), 0);
    sort(ord.begin() + 1, ord.end(), [] (int i, int j) { return g[i].size() > g[j].size(); });

    int ans = g[ord[1]].size() + g[ord[2]].size() - 2;
    DFS(ord[1]);

    bool ok = false;
    for (int i = 2; i <= n; ++i) {
        if (par[ord[i]] != ord[1] && g[ord[i]].size() == g[ord[2]].size()) {
            ans++;
            ok = true;
            break;
        }
    }

    if (!ok && g[ord[2]].size() == g[ord[1]].size()) {
        DFS(ord[2]);
        for (int i = 1; i <= n; ++i) {
            if (i != 2 && par[ord[i]] != ord[2] && g[ord[i]].size() == g[ord[2]].size()) {
                ans++;
                break;
            }
        }
    }

    cout << ans << "\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t;
    cin >> t;

    while (t--) {
        Solve();
    }
}

Answer: 2


#include <bits/stdc++.h>

using namespace std;

bool isInSet(pair<int,int> pr, set<pair<int,int>> &s) {
    return s.find(pr) != s.end();
}

void solve(){
    int n;
    cin>>n;
    set<pair<int, int>> edge_set;
    vector<pair<int,int>> deg(n);
    for(int i=0;i<n;i++) {
        deg[i].second = i;
        deg[i].first = 0;
    }
    for (int i=1;i<n;i++) {
        int u,v;
        cin>>u>>v;
        --u,--v;
        edge_set.insert(make_pair(u,v));
        edge_set.insert(make_pair(v,u));
        deg[u].first++;
        deg[v].first++;
    }
    if (n==2) {
        cout<<"0\n";
        return;
    }
    sort(deg.begin(), deg.end());
    int ans = 0;
    for(int i=n-1;i>=n-3;i--) {
        for(int j=i-1;j>=n-3;j--) {
            ans = max(ans, deg[i].first + deg[j].first - (isInSet(make_pair(deg[i].second, deg[j].second), edge_set) ? 1: 0));
        }
    }
    cout<<(ans-1)<<'\n';
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

bool isInSet(pair<int,int> pr, set<pair<int,int>> &s) {
    return s.find(pr) != s.end();
}

void solve(){
    int n;
    cin>>n;
    set<pair<int, int>> edge_set;
    vector<pair<int,int>> deg(n);
    for(int i=0;i<n;i++) {
        deg[i].second = i;
        deg[i].first = 0;
    }
    for (int i=1;i<n;i++) {
        int u,v;
        cin>>u>>v;
        --u,--v;
        edge_set.insert(make_pair(u,v));
        edge_set.insert(make_pair(v,u));
        deg[u].first++;
        deg[v].first++;
    }
    if (n==2) {
        cout<<"0\n";
        return;
    }
    sort(deg.begin(), deg.end());
    int ans = 0;
    for(int i=n-2;i>=0;i--) {
        int j=n-1;
        ans = max(ans, deg[i].first + deg[j].first - (isInSet(make_pair(deg[i].second, deg[j].second), edge_set) ? 1: 0));
    }
    ans = max(ans, deg[n-2].first + deg[n-3].first - (isInSet(make_pair(deg[n-2].second, deg[n-3].second), edge_set) ? 1: 0));
    cout<<(ans-1)<<'\n';
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
}

Answer: 2


#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int main() {
    ll t;
    cin >> t;

    while (t--) {
        ll z;
        cin >> z;
        vector<set<ll>> tree(z + 1);

        for (ll i = 0; i < z - 1; i++) {
            ll x, y;
            cin >> x >> y;
            tree[x].insert(y);
            tree[y].insert(x);
        }

        ll connected = 0, idx = 1;

        // Finding the most connected node
        for (ll i = 1; i <= z; i++) {
            if (connected < (ll)tree[i].size()) {
                connected = tree[i].size();
                idx = i;
            }
        }

        ll ans = 0;
        ans += tree[idx].size();

        // Remove first selected node's edges
        for (auto x : tree[idx]) {
            tree[x].erase(idx);
        }
        tree[idx].clear();

        // Find the next most connected node
        connected = 0, idx = 1;
        for (ll i = 1; i <= z; i++) {
            if (connected < (ll)tree[i].size()) {
                connected = tree[i].size();
                idx = i;
            }
        }

        ans += tree[idx].size();
        cout << ans-1 << endl;
    }

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int main() {
	ll t;
	cin >> t;

	while (t--) {
		ll z;
		cin >> z;
		vector<set<ll>> tree(z + 1);

		for (ll i = 0; i < z - 1; i++) {
			ll x, y;
			cin >> x >> y;
			tree[x].insert(y);
			tree[y].insert(x);
		}
		vector<set<ll>> tree1=tree;
		ll connected = 0, idx = 1;

		// Finding the most connected node
		for (ll i = 1; i <= z; i++) {
			if (connected < (ll)tree[i].size()) {
				connected = tree[i].size();
				idx = i;
			}
		}

		ll ans = 1;
		ans += tree[idx].size()-1;
		// Remove first selected node's edges
		for (auto x : tree[idx]) {
			tree[x].erase(idx);
		}
		tree[idx].clear();

		// Find the next most connected node
		connected = 0, idx = 1;
		for (ll i = 1; i <= z; i++) {
			if (connected < (ll)tree[i].size()) {
				connected = tree[i].size();
				idx = i;
			}
		}

		ans += tree[idx].size()-1;

		 connected = 0;
		  idx = 1;

		// Finding the most connected node
		for (ll i = z; i >=1; i--) {
			if (connected < (ll)tree1[i].size()) {
				connected = tree1[i].size();
				idx = i;
			}
		}

		ll ans1 = 1;
		ans1 += tree1[idx].size()-1;
		// Remove first selected node's edges
		for (auto x : tree1[idx]) {
			tree1[x].erase(idx);
		}
		tree1[idx].clear();

		// Find the next most connected node
		connected = 0, idx = 1;
		for (ll i = 1; i <= z; i++) {
			if (connected < (ll)tree1[i].size()) {
				connected = tree1[i].size();
				idx = i;
			}
		}

		ans1 += tree1[idx].size()-1;
		cout <<max(ans,ans1)<< endl;
	}

	return 0;
}

Answer: 2


#include<bits/stdc++.h>

using namespace std;
using ll = long long;

int main(){
    ll t;
    cin>>t;
    while(t--){
        ll n, x, y, ans = 0, maxNeighbors = -1, eleRemoved = 1;
        cin>>n;
        vector<vector<ll>> adj(n + 1);
        vector<ll> neighbors(n + 1, 0);
        for(ll i = 0 ; i < n - 1 ; i++){
            cin>>x>>y;
            adj[x].push_back(y);
            adj[y].push_back(x);
        }
        for(ll i = 1 ; i <= n ; i++) neighbors[i] = adj[i].size();
        for(ll k = 1 ; k <= 2 ; k++){
            maxNeighbors = -1, eleRemoved = 1;
            for(ll i = 1 ; i <= n ; i++){
                if(maxNeighbors < neighbors[i]){
                    maxNeighbors = neighbors[i];
                    eleRemoved = i;
                }
            }
            ans += maxNeighbors;
            for(auto it : adj[eleRemoved]) neighbors[it]--;
            neighbors[eleRemoved] = -1;
        }
        ans -= 1;
        cout<<ans<<endl;
    }
}

#include<bits/stdc++.h>

using namespace std;
using ll = long long;

int main(){
    ll t;
    cin>>t;
    while(t--){
        ll n, x, y, ans = 0, maxNeighbors = -1, eleRemoved = 1;
        cin>>n;
        vector<vector<ll>> adj(n + 1);
        vector<ll> neighbors(n + 1, 0);
        for(ll i = 0 ; i < n - 1 ; i++){
            cin>>x>>y;
            adj[x].push_back(y);
            adj[y].push_back(x);
        }
        for(ll i = 1 ; i <= n ; i++) neighbors[i] = adj[i].size();
        for(ll k = 1 ; k <= 2 ; k++){
            maxNeighbors = -1, eleRemoved = 1;
            for(ll i = 1 ; i <= n ; i++){
                if(maxNeighbors < neighbors[i]){
                    maxNeighbors = neighbors[i];
                    eleRemoved = i;
                }
                else if(maxNeighbors == neighbors[i]){
                    ll sum1 = 0, sum2 = 0;
                    for(auto it : adj[eleRemoved]) sum1 += neighbors[it];
                    for(auto it : adj[i]) sum2 += neighbors[it];
                    if(sum2 < sum1) eleRemoved = i;
                }
            }
            ans += maxNeighbors;
            for(auto it : adj[eleRemoved]) neighbors[it]--;
            neighbors[eleRemoved] = -1;
        }
        ans -= 1;
        cout<<ans<<endl;
    }
}

Answer: 2


#include<bits/stdc++.h>
using namespace std;
vector<int> num;
int cmp(int a,int b)
{
    if(num[a]>num[b]) return 1;
    else return 0;
}
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        num.resize(n+1);
        for(int i=1;i<=n;i++)
        {
            num[i] = 0;
        }
        vector<int> big(n+1);
        for(int i=1;i<=n;i++)
        {
            big[i] = i;
        }
        map<pair<int,int>,int> mp;
        for(int i=1;i<n;i++)
        {
            int u,v;
            cin >> u >> v;
            mp[{v,u}]++;
            mp[{u,v}]++;
            num[u]++;
            num[v]++;
        }
        int ans = 1;
        sort(big.begin()+1,big.end(),cmp);
        if(num[big[1]]!=num[big[2]])
        {
            // cout <<"num "<< num[big[1]] << ' ' << num[big[2]] <<'\n';
            ans += num[big[1]]+num[big[2]]-3;
            int i = 2;
            while(i<=n&&num[big[i]]==num[big[2]])
            {
                if(!mp[{big[i],big[1]}])
                {
                    ans++;
                    break;
                }
                i++;
            }
            cout << ans <<'\n';
        }
        else
        {
            ans += 2*num[big[1]]-3;
            int k = 2;
            while(k<=n&&num[big[k]]==num[big[1]])
            {
                k++;
            }
            k--;
            if(k>=3) ans++;
            else
            {
                if(mp[{big[1],big[2]}]==0) ans++;
            }
            // int edge = 0;
            // for(auto& [a,_] : mp)
            // {
            //     if(a.first<=k&&a.second<=k) edge++;
            // }

            // if()
            cout << ans << '\n';
        }
    }
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
vector<int> num;
int cmp(int a,int b)
{
    if(num[a]>num[b]) return 1;
    else return 0;
}
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        num.resize(n+1);
        for(int i=1;i<=n;i++)
        {
            num[i] = 0;
        }
        vector<int> big(n+1);
        for(int i=1;i<=n;i++)
        {
            big[i] = i;
        }
        map<pair<int,int>,int> mp;
        for(int i=1;i<n;i++)
        {
            int u,v;
            cin >> u >> v;
            mp[{v,u}]++;
            mp[{u,v}]++;
            num[u]++;
            num[v]++;
        }
        int ans = 1;
        sort(big.begin()+1,big.end(),cmp);
        if(num[big[1]]!=num[big[2]])
        {
            // cout <<"num "<< num[big[1]] << ' ' << num[big[2]] <<'\n';
            ans += num[big[1]]+num[big[2]]-3;
            int i = 2;
            while(i<=n&&num[big[i]]==num[big[2]])
            {
                if(!mp[{big[i],big[1]}])
                {
                    ans++;
                    break;
                }
                i++;
            }
            cout << ans <<'\n';
        }
        else
        {
            ans += 2*num[big[1]]-3;
            int k = 2;
            while(k<=n&&num[big[k]]==num[big[1]])
            {
                k++;
            }
            k--;
            if(k>=3) ans++;
            // int edge = 0;
            // for(auto& [a,_] : mp)
            // {
            //     if(a.first<=k&&a.second<=k) edge++;
            // }

            // if()
            cout << ans << '\n';
        }
    }
    return 0;
}

Answer: 1


#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#include<bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
 typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag,
 __gnu_pbds::tree_order_statistics_node_update> ordered_set;*/
typedef long long ll;
#define pb push_back
typedef long double ld;
/*int smallestdivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;

    // iterate from 3 to sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return i;
    }

    return n;
}*/
/*int parent[200005];
int siz[200005];
void make_set(ll n){
for(int i=1;i<=n;i++){parent[i]=i;siz[i]=1;}
}

int find_set(ll v){
    if(v==parent[v])
    return v;
    return parent[v]=find_set(parent[v]);

}

void union_set(ll a,ll b){
    a=find_set(a);
    b=find_set(b);
    if(a!=b){
        if(siz[a]<siz[b])
        swap(a,b);
        parent[b]=a;
        siz[a]+=siz[b];
    }
}
ll kruskal(vector<pair<ll,pair<ll,ll>>>& edges,ll n){
    sort(edges.begin(),edges.end());
    make_set(n);
    ll sum=0;
    for(auto x:edges){
        if(find_set(x.second.first)==find_set(x.second.second)) continue;
        union_set(x.second.first,x.second.second);
        sum+=x.first;
    }
    return sum;
}*/
int vis[300005];//vector<ll> level(300005);
//queue<ll> q;
/*void bfs(vector<vector<ll>>& adj,ll& ans){
    ll src=0;
    vis[src]=1;
   // level[src]=0;
    q.push(src);
    while(!q.empty()){
       u=q.top();
        q.pop();vis[u]=1;
        for(int v:adj[u]){
            if(vis[v]==1) continue;
           // level[v]=level[u]+1;
            q.push(v);
        }
    }
}*/
void dfs(ll u,vector<vector<int>>& adj){
   vis[u]=1;

   for(auto v:adj[u]){

    if(vis[v]==1) continue;

     dfs(v,adj);

   }

   //saari v se action lene k baad kuch u ka check krna h toh this pos-->dp or any

}
/*void dijkstras(vector<vector<pair<ll,ll>>> adj,ll point,vector<vector<ll>> &dis){

  priority_queue<pair<ll,ll>> pq;
   int src=point;
   dis[src][src]=0;
   pq.push({0,src});

   while(!pq.empty()){

     int u=pq.top().second;
     int d=-pq.top().first;
     pq.pop();

     if(dis[src][u]<d) continue;

     for(auto v:adj[u]){

        if(dis[src][v.first]<=dis[src][u]+v.second) continue;
        dis[src][v.first]=dis[src][u]+v.second;
        pq.push({-dis[src][v.first],v.first});

     }

   }

}*/
signed main(){ios::sync_with_stdio(0); cin.tie(0); //cout.tie(0);cout << fixed << setprecision(15);
ll tt=1;cin>>tt;string pi = "3.141592653589793238462643383279";
while(tt--){ ll n;cin>>n;vector<vector<int>> adj(n);vector<pair<ll,ll>> p;map<pair<ll,ll>,int> m;
for(int i=0;i<n-1;i++){
    ll x,y;cin>>x>>y;x--;y--;p.pb({x,y});m[{x,y}]++;m[{y,x}]++;
    adj[x].pb(y);adj[y].pb(x);

}
vector<pair<ll,ll>> v;
for(int i=0;i<n;i++) v.pb({adj[i].size(),i});
sort(v.begin(),v.end());ll ans=0;
for(int i=0;i<n;i++){
    for(int j=i+1;j<n;j++){
        if(m[{v[i].second,v[j].second}]==0){
            ll k=v[i].first+v[j].first-1;
            ans=max(ans,k);break;
        }
    }
}
for(int i=0;i<n-1;i++){
    ll k=adj[p[i].first].size()+adj[p[i].second].size()-2;
    ans=max(ans,k);
}
cout<<ans<<'\n';

}
 return 0;
}

/*------------>>>>>DSU.....................
int parent[n];
int size[n];
void make_set(int n){
for(int i=1;i<=n;i++){parent[i]=i;size[i]=1;}
}

int find_set(int v){
    if(v==parent[v])
    return v;
    return parent[v]=find_set(parent[v]);

}

void union_set(int a,int b){
    a=find_set(a);
    b=find_set(b);
    if(a!=b){
        if(size[a]<size[b])
        swap(a,b);
        parent[b]=a;
        size[a]+=size[b];
    }
}
*/
/*void dijkstras(vector<vector<pair<ll,ll>>>& adj,vector<ll>& s,vector<vector<ll>>& dis,ll& n){
     vector<vector<ll>> vis(n,vector<ll> (n,0));
    priority_queue<pair<ll,pair<ll,ll>>> pq;
    int src=0;
    dis[src][0]=0;
    pq.push({0,{src,0}});

    while(!pq.empty()){
        ll u=pq.top().second.first;
        ll d=-pq.top().first;
       ll bike= pq.top().second.second;

        pq.pop();

        if(vis[u][bike]!=0) continue;// this is an useful optimisation

        for(auto v:adj[u]){
             if(s[u]>s[bike]){
                dis[v.first][bike]=min(dis[v.first][bike],dis[u][bike]+v.second*s[bike]);
                pq.push({-dis[v.first][bike],{v.first,bike}});
             }
             else{
                dis[v.first][u]=min(dis[v.first][u],dis[u][bike]+v.second*s[u]);
                pq.push({-dis[v.first][u],{v.first,u}});
             }
           vis[u][bike]++;

        }
    }
}*/

/*ll sum_digit(ll n)
{
    ll num=0;
    while(n>0)
    {
        num+=n%10;
        n=n/10;
    }
    return num;
}*/
//kisi bhi tough prob me max ya min value k liye binary search is always there to help.....
//first bit of any number is always a divisor of that number........
//What is convex hull trick?????????????????
//dp mein hum kya krna chah rhe iski puri info honi chahiye kisi bhi point par aese sochna pdega.....states k liye>>>>>>>

//r.insert(r.begin(), 1 - d);----------->>>>to insert element in starting of an vevtor..........
/*for(auto it=m.rbegin();it!=m.rend();++it){
  for(int i=0;i<it->second.size();i++){
    v2.pb(it->second[i]);
  }
}*/
//largest power of a prime number that divides fact! is legendres formula.........
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
*/
//sometimes long long ko int krne par tle nhi aata(kaafi ajeeb :())
 // Binary search me r=n+1,l=0&&condition:l+1<r;

// for(int i=2;i<=N;i++){
  //  if(prime[i]==0){
    //v.pb(i);
    //for(int j=2*i;j<=N;j+=i){prime[j]++;}
    //}
 //}
 /*int smallestdivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;

    // iterate from 3 to sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return i;
    }

    return n;
}*/
/*ll binpow(ll a,ll b,ll m = LLONG_MAX){
    ll res = 1;
    while (b){
        if (b&1) res = (res*a)%m;
        a = (a*a)%m;
        b>>=1;
    }
    return res;
}*/
/*for(int i=0;i<n;i++){
  if(m[s[i]]==0){
 if(i1==-1){ a[i]+=i+(n-1-i)*(i)+n-1-i;a[i]++;i1=i;}
 else{
  a[i]+=i-i1-1+(n-1-i)*(i-i1-1)+n-1-i;a[i]++;i1=i;
 }
  }
}
for(int i=0;i<n;i++){
  ans-=a[i];
}*/
/////Favorites>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>............................................
/*ll n,k;cin>>n>>k;
 if(n%2==0){
  if(k%n)cout<<k%n<<'\n';
  else{cout<<n<<'\n';}
 }
 else{ll n1=n-1;n1/=2;ll a=(k-1)/n1;ll b=k%n;
  if(b==0){b=n;}b+=a;b%=n;if(b==0){b=n;}
  cout<<b<<'\n';

 }*/
 /*const ll N=2*(1e5+10);
 ll a[N];vector<ll> p(N,0);
 vector<vector<ll>> g(N);
 void dfs(ll vertex){
  for(int child: g[vertex]){
    if(child!=p[vertex]){
      p[child]=vertex;
    dfs(child);
    a[vertex]+=a[child];
    }
  }
  if(g[vertex].size()==1&&a[vertex]==0){
    a[vertex]++;
  }
 }*/
 /*#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
//using namespace __gnu_pbds;
//template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define vll vector<long long>
#define vvll vector<vector<long long>>
#define mll map<long long,long long>
#define max(a,b) ((a>b)?a:b)
#define min(a,b) ((a>b)?b:a)
#define pb push_back
#define prll pair<long long,long long>
typedef long long ll;
typedef long double ld;
#define int long long
#define mini(x,y) x = min(x,y)
#define maxi(x,y) x = max(x,y)
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
#define ff first
#define ss second
#define rep(i,a,n)   for(ll i=a; i<n; i++)
#define rrep(i,a,n)  for(ll i=n-1; i>=a; i--)
typedef map<string,ll> msl;
#define all(con) con.begin(),con.end()
#define done(x) {cout << x << endl;return;}
#define sz(x) ((long long)x.size())
#define trav(a,x) for(auto &a:x)
const ll mx=200005;
const ll mod=1e9 + 7;
const ld PI = 3.141592653589793238460;
//DEBUG FUNCTIONS START
#define cerr cout
void __print(ll x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "\n";}
template <typename T, typename... V>
void print(T t, V... v) {_print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
//#define deb(x...) cerr << "[" << #x << "] = "; _print(x)
#define deb(x...)  _print(x)
#else
#define deb(x...)
#endif
// DEBUG FUNCTIONS END
mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
uniform_int_distribution<int> rng(0,1);
// ll x=rng(mt);
ll gcd(ll a, ll b){
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
ll extgcd(ll a,ll b,ll& x,ll& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll x1, y1;
    ll d = extgcd(b, a % b, x1, y1);
    x = y1;
    y = x1 - y1 * (a / b);
    return d;
}
bool isPrime(ll n){
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
    if (n % 2 == 0 || n % 3 == 0)
        return false;
    for (ll i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
    return true;
}
bool isPowerOfTwo(ll n) {
   if(n==0)
   return false;
   return ((ll)ceil(log2(n)) == (ll)floor(log2(n)));
}
ll powm(ll a,ll b) {
    ll res = 1;
    while (b) {
        if (b & 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res;
}
ll divide(ll a,ll b) {
    return (a % mod) * powm(b, mod - 2) % mod;
}
ll mul(ll a,ll b) {
    return ((a % mod) * (b % mod)) % mod;
}

ll add(ll a,ll b) {
    return (a % mod + b % mod) % mod;
}
ll Totfun(ll n){
    ll z=n;
    if(n%2==0){
        while(n%2==0){
            n/=2;
        }
        z/=2;
    }
    for(ll i=3;i*i<=n;i+=2){
        if(isPrime(i)&&n%i==0){
          while(n%i==0){
            n/=i;
          }
        z-=z/i;
        }
    }
    if(n>1){
        z-=z/n;
    }
    return z;
}
ll fact[mx];
ll nCr(ll n,ll r){
    if(r>n||r<0) return 0;
    ll z=fact[n];
    z=mul(z,powm(fact[n-r],mod-2));
    z=mul(z,powm(fact[r],mod-2));
    return z;
}
/*
fact[0]=1;
rep(i,1,mx){
 fact[i]=mul(i,fact[i-1]);
}
*/
/*
vll a[mx];
ll l[mx],d[mx];
void dfs(ll x,ll y){
   l[x]=1; d[x]=y;
   for(ll i:a[x])
   if(!l[i])
   dfs(i,y+1);
}
void bfs(ll x){
    queue<ll> q;
    q.push(x);
    l[x]=1;
    d[x]=0;
    while(!q.empty()){
        ll cur=q.front();
        q.pop();
        for(ll i : a[cur]){
            if(1-l[i]){
                q.push(i);
                d[i]=d[cur]+1;
                l[i]=1;
            }
        }
    }
}
*/

/*struct fenwick{

    int n;
    vll bit;

    fenwick(int _n){
        n = _n + 5;
        bit.resize(n);
    }

    int qry(int i){
        int res = 0;
        for(++i; i; i -= i & - i)
            res += bit[i];
        return res;
    }

    void upd(int i, int val){
        for(++i; i < n; i += i & -i)
            bit[i] += val;
    }
};
ll m;
void dfs(ll x,vector<vector<int>>& adj,vector<vector<int>>& dp){
    rep(i,1,m+1) dp[x][i]=1;
    for(ll i:adj[x]){
        dfs(i,adj,dp);
        if(i<x){
            rep(j,1,m+1) dp[x][j]=mul(dp[x][j],dp[i][j-1]);
        }
        else{
            rep(j,1,m+1) dp[x][j]=mul(dp[x][j],dp[i][j]);
        }
    }
    rep(i,1,m+1) dp[x][i]=add(dp[x][i],dp[x][i-1]);
}
void solve(){
   ll n;
   cin>>n;
   ll a[n];
   //ll m;
   cin>>m;
   rep(i,0,n) cin>>a[i];
   vll pos[m+1];
   rep(i,0,n){
    pos[a[i]].pb(i);
   }
   fenwick ft(n);
   ll pr[n];
   for(int i=m;i>0;i--){
    for(int j:pos[i]){
        ll lo,hi,mid,l=-1,r=-1;
        if(ft.qry(n-1)-ft.qry(j)>0){
            lo=j+1;
            hi=n-1;
            while(lo<hi){
                mid=(lo+hi)/2;
                if(ft.qry(mid)-ft.qry(j)>0) hi=mid;
                else lo=mid+1;
            }
            l=lo;
        }
        if(ft.qry(j)>0){
            lo=0;
            hi=j-1;
            while(lo<hi){
                mid=(lo+hi+1)/2;
                if(ft.qry(j)-ft.qry(mid-1)>0) lo=mid;
                else hi=mid-1;
            }
            r=lo;
        }
        if(l==-1&&r==-1) pr[j]=-1;
        else if(l==-1) pr[j]=r;
        else if(r==-1) pr[j]=l;
        else{
            if(a[r]<a[l]) pr[j]=r;
            else pr[j]=l;
        }
        //cout<<l<<" "<<r<<" "<<j<<"\n";
        ft.upd(j,1);
    }
   }
   vector<vector<int>> adj;
   adj.resize(n);
   vector<vector<int>> dp(n,vector<int>(m+1));
   ll x=0;
   rep(i,0,n){
    if(pr[i]!=-1) adj[pr[i]].pb(i);
    else{
        x=i;
    }
   }
   //rep(i,0,n) cout<<pr[i]<<" ";
   dfs(x,adj,dp);
   //if(dp[x][m]==677569164) done(351025663);
   done(dp[x][m]);
   //351025663
}
signed main(){
   ios_base::sync_with_stdio(false);
   cin.tie(NULL);
   cout.tie(NULL);
   cout<<fixed<<setprecision(20);
   ll t = 1;
   cin >> t;
   while (t--)
       solve();
   return 0;
}*/

#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#include<bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
 typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag,
 __gnu_pbds::tree_order_statistics_node_update> ordered_set;*/
typedef long long ll;
#define pb push_back
typedef long double ld;
/*int smallestdivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;

    // iterate from 3 to sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return i;
    }

    return n;
}*/
/*int parent[200005];
int siz[200005];
void make_set(ll n){
for(int i=1;i<=n;i++){parent[i]=i;siz[i]=1;}
}

int find_set(ll v){
    if(v==parent[v])
    return v;
    return parent[v]=find_set(parent[v]);

}

void union_set(ll a,ll b){
    a=find_set(a);
    b=find_set(b);
    if(a!=b){
        if(siz[a]<siz[b])
        swap(a,b);
        parent[b]=a;
        siz[a]+=siz[b];
    }
}
ll kruskal(vector<pair<ll,pair<ll,ll>>>& edges,ll n){
    sort(edges.begin(),edges.end());
    make_set(n);
    ll sum=0;
    for(auto x:edges){
        if(find_set(x.second.first)==find_set(x.second.second)) continue;
        union_set(x.second.first,x.second.second);
        sum+=x.first;
    }
    return sum;
}*/
int vis[300005];//vector<ll> level(300005);
//queue<ll> q;
/*void bfs(vector<vector<ll>>& adj,ll& ans){
    ll src=0;
    vis[src]=1;
   // level[src]=0;
    q.push(src);
    while(!q.empty()){
       u=q.top();
        q.pop();vis[u]=1;
        for(int v:adj[u]){
            if(vis[v]==1) continue;
           // level[v]=level[u]+1;
            q.push(v);
        }
    }
}*/
void dfs(ll u,vector<vector<int>>& adj){
   vis[u]=1;

   for(auto v:adj[u]){

    if(vis[v]==1) continue;

     dfs(v,adj);

   }

   //saari v se action lene k baad kuch u ka check krna h toh this pos-->dp or any

}
/*void dijkstras(vector<vector<pair<ll,ll>>> adj,ll point,vector<vector<ll>> &dis){

  priority_queue<pair<ll,ll>> pq;
   int src=point;
   dis[src][src]=0;
   pq.push({0,src});

   while(!pq.empty()){

     int u=pq.top().second;
     int d=-pq.top().first;
     pq.pop();

     if(dis[src][u]<d) continue;

     for(auto v:adj[u]){

        if(dis[src][v.first]<=dis[src][u]+v.second) continue;
        dis[src][v.first]=dis[src][u]+v.second;
        pq.push({-dis[src][v.first],v.first});

     }

   }

}*/
signed main(){ios::sync_with_stdio(0); cin.tie(0); //cout.tie(0);cout << fixed << setprecision(15);
ll tt=1;cin>>tt;string pi = "3.141592653589793238462643383279";
while(tt--){ ll n;cin>>n;vector<vector<int>> adj(n);vector<pair<ll,ll>> p;map<pair<ll,ll>,int> m;
for(int i=0;i<n-1;i++){
    ll x,y;cin>>x>>y;x--;y--;p.pb({x,y});m[{x,y}]++;m[{y,x}]++;
    adj[x].pb(y);adj[y].pb(x);

}
vector<pair<ll,ll>> v;
for(int i=0;i<n;i++) v.pb({adj[i].size(),i});
sort(v.rbegin(),v.rend());ll ans=0;
for(int i=0;i<n;i++){
    for(int j=i+1;j<n;j++){
        if(m[{v[i].second,v[j].second}]==0){
            ll k=v[i].first+v[j].first-1;
            ans=max(ans,k);break;
        }
    }
}
for(int i=0;i<n-1;i++){
    ll k=adj[p[i].first].size()+adj[p[i].second].size()-2;
    ans=max(ans,k);
}
cout<<ans<<'\n';

}
 return 0;
}

/*------------>>>>>DSU.....................
int parent[n];
int size[n];
void make_set(int n){
for(int i=1;i<=n;i++){parent[i]=i;size[i]=1;}
}

int find_set(int v){
    if(v==parent[v])
    return v;
    return parent[v]=find_set(parent[v]);

}

void union_set(int a,int b){
    a=find_set(a);
    b=find_set(b);
    if(a!=b){
        if(size[a]<size[b])
        swap(a,b);
        parent[b]=a;
        size[a]+=size[b];
    }
}
*/
/*void dijkstras(vector<vector<pair<ll,ll>>>& adj,vector<ll>& s,vector<vector<ll>>& dis,ll& n){
     vector<vector<ll>> vis(n,vector<ll> (n,0));
    priority_queue<pair<ll,pair<ll,ll>>> pq;
    int src=0;
    dis[src][0]=0;
    pq.push({0,{src,0}});

    while(!pq.empty()){
        ll u=pq.top().second.first;
        ll d=-pq.top().first;
       ll bike= pq.top().second.second;

        pq.pop();

        if(vis[u][bike]!=0) continue;// this is an useful optimisation

        for(auto v:adj[u]){
             if(s[u]>s[bike]){
                dis[v.first][bike]=min(dis[v.first][bike],dis[u][bike]+v.second*s[bike]);
                pq.push({-dis[v.first][bike],{v.first,bike}});
             }
             else{
                dis[v.first][u]=min(dis[v.first][u],dis[u][bike]+v.second*s[u]);
                pq.push({-dis[v.first][u],{v.first,u}});
             }
           vis[u][bike]++;

        }
    }
}*/

/*ll sum_digit(ll n)
{
    ll num=0;
    while(n>0)
    {
        num+=n%10;
        n=n/10;
    }
    return num;
}*/
//kisi bhi tough prob me max ya min value k liye binary search is always there to help.....
//first bit of any number is always a divisor of that number........
//What is convex hull trick?????????????????
//dp mein hum kya krna chah rhe iski puri info honi chahiye kisi bhi point par aese sochna pdega.....states k liye>>>>>>>

//r.insert(r.begin(), 1 - d);----------->>>>to insert element in starting of an vevtor..........
/*for(auto it=m.rbegin();it!=m.rend();++it){
  for(int i=0;i<it->second.size();i++){
    v2.pb(it->second[i]);
  }
}*/
//largest power of a prime number that divides fact! is legendres formula.........
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
*/
//sometimes long long ko int krne par tle nhi aata(kaafi ajeeb :())
 // Binary search me r=n+1,l=0&&condition:l+1<r;

// for(int i=2;i<=N;i++){
  //  if(prime[i]==0){
    //v.pb(i);
    //for(int j=2*i;j<=N;j+=i){prime[j]++;}
    //}
 //}
 /*int smallestdivisor(int n)
{
    // if divisible by 2
    if (n % 2 == 0)
        return 2;

    // iterate from 3 to sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0)
            return i;
    }

    return n;
}*/
/*ll binpow(ll a,ll b,ll m = LLONG_MAX){
    ll res = 1;
    while (b){
        if (b&1) res = (res*a)%m;
        a = (a*a)%m;
        b>>=1;
    }
    return res;
}*/
/*for(int i=0;i<n;i++){
  if(m[s[i]]==0){
 if(i1==-1){ a[i]+=i+(n-1-i)*(i)+n-1-i;a[i]++;i1=i;}
 else{
  a[i]+=i-i1-1+(n-1-i)*(i-i1-1)+n-1-i;a[i]++;i1=i;
 }
  }
}
for(int i=0;i<n;i++){
  ans-=a[i];
}*/
/////Favorites>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>............................................
/*ll n,k;cin>>n>>k;
 if(n%2==0){
  if(k%n)cout<<k%n<<'\n';
  else{cout<<n<<'\n';}
 }
 else{ll n1=n-1;n1/=2;ll a=(k-1)/n1;ll b=k%n;
  if(b==0){b=n;}b+=a;b%=n;if(b==0){b=n;}
  cout<<b<<'\n';

 }*/
 /*const ll N=2*(1e5+10);
 ll a[N];vector<ll> p(N,0);
 vector<vector<ll>> g(N);
 void dfs(ll vertex){
  for(int child: g[vertex]){
    if(child!=p[vertex]){
      p[child]=vertex;
    dfs(child);
    a[vertex]+=a[child];
    }
  }
  if(g[vertex].size()==1&&a[vertex]==0){
    a[vertex]++;
  }
 }*/
 /*#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
//using namespace __gnu_pbds;
//template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define vll vector<long long>
#define vvll vector<vector<long long>>
#define mll map<long long,long long>
#define max(a,b) ((a>b)?a:b)
#define min(a,b) ((a>b)?b:a)
#define pb push_back
#define prll pair<long long,long long>
typedef long long ll;
typedef long double ld;
#define int long long
#define mini(x,y) x = min(x,y)
#define maxi(x,y) x = max(x,y)
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
#define ff first
#define ss second
#define rep(i,a,n)   for(ll i=a; i<n; i++)
#define rrep(i,a,n)  for(ll i=n-1; i>=a; i--)
typedef map<string,ll> msl;
#define all(con) con.begin(),con.end()
#define done(x) {cout << x << endl;return;}
#define sz(x) ((long long)x.size())
#define trav(a,x) for(auto &a:x)
const ll mx=200005;
const ll mod=1e9 + 7;
const ld PI = 3.141592653589793238460;
//DEBUG FUNCTIONS START
#define cerr cout
void __print(ll x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "\n";}
template <typename T, typename... V>
void print(T t, V... v) {_print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
//#define deb(x...) cerr << "[" << #x << "] = "; _print(x)
#define deb(x...)  _print(x)
#else
#define deb(x...)
#endif
// DEBUG FUNCTIONS END
mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
uniform_int_distribution<int> rng(0,1);
// ll x=rng(mt);
ll gcd(ll a, ll b){
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
ll extgcd(ll a,ll b,ll& x,ll& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll x1, y1;
    ll d = extgcd(b, a % b, x1, y1);
    x = y1;
    y = x1 - y1 * (a / b);
    return d;
}
bool isPrime(ll n){
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
    if (n % 2 == 0 || n % 3 == 0)
        return false;
    for (ll i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
    return true;
}
bool isPowerOfTwo(ll n) {
   if(n==0)
   return false;
   return ((ll)ceil(log2(n)) == (ll)floor(log2(n)));
}
ll powm(ll a,ll b) {
    ll res = 1;
    while (b) {
        if (b & 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res;
}
ll divide(ll a,ll b) {
    return (a % mod) * powm(b, mod - 2) % mod;
}
ll mul(ll a,ll b) {
    return ((a % mod) * (b % mod)) % mod;
}

ll add(ll a,ll b) {
    return (a % mod + b % mod) % mod;
}
ll Totfun(ll n){
    ll z=n;
    if(n%2==0){
        while(n%2==0){
            n/=2;
        }
        z/=2;
    }
    for(ll i=3;i*i<=n;i+=2){
        if(isPrime(i)&&n%i==0){
          while(n%i==0){
            n/=i;
          }
        z-=z/i;
        }
    }
    if(n>1){
        z-=z/n;
    }
    return z;
}
ll fact[mx];
ll nCr(ll n,ll r){
    if(r>n||r<0) return 0;
    ll z=fact[n];
    z=mul(z,powm(fact[n-r],mod-2));
    z=mul(z,powm(fact[r],mod-2));
    return z;
}
/*
fact[0]=1;
rep(i,1,mx){
 fact[i]=mul(i,fact[i-1]);
}
*/
/*
vll a[mx];
ll l[mx],d[mx];
void dfs(ll x,ll y){
   l[x]=1; d[x]=y;
   for(ll i:a[x])
   if(!l[i])
   dfs(i,y+1);
}
void bfs(ll x){
    queue<ll> q;
    q.push(x);
    l[x]=1;
    d[x]=0;
    while(!q.empty()){
        ll cur=q.front();
        q.pop();
        for(ll i : a[cur]){
            if(1-l[i]){
                q.push(i);
                d[i]=d[cur]+1;
                l[i]=1;
            }
        }
    }
}
*/

/*struct fenwick{

    int n;
    vll bit;

    fenwick(int _n){
        n = _n + 5;
        bit.resize(n);
    }

    int qry(int i){
        int res = 0;
        for(++i; i; i -= i & - i)
            res += bit[i];
        return res;
    }

    void upd(int i, int val){
        for(++i; i < n; i += i & -i)
            bit[i] += val;
    }
};
ll m;
void dfs(ll x,vector<vector<int>>& adj,vector<vector<int>>& dp){
    rep(i,1,m+1) dp[x][i]=1;
    for(ll i:adj[x]){
        dfs(i,adj,dp);
        if(i<x){
            rep(j,1,m+1) dp[x][j]=mul(dp[x][j],dp[i][j-1]);
        }
        else{
            rep(j,1,m+1) dp[x][j]=mul(dp[x][j],dp[i][j]);
        }
    }
    rep(i,1,m+1) dp[x][i]=add(dp[x][i],dp[x][i-1]);
}
void solve(){
   ll n;
   cin>>n;
   ll a[n];
   //ll m;
   cin>>m;
   rep(i,0,n) cin>>a[i];
   vll pos[m+1];
   rep(i,0,n){
    pos[a[i]].pb(i);
   }
   fenwick ft(n);
   ll pr[n];
   for(int i=m;i>0;i--){
    for(int j:pos[i]){
        ll lo,hi,mid,l=-1,r=-1;
        if(ft.qry(n-1)-ft.qry(j)>0){
            lo=j+1;
            hi=n-1;
            while(lo<hi){
                mid=(lo+hi)/2;
                if(ft.qry(mid)-ft.qry(j)>0) hi=mid;
                else lo=mid+1;
            }
            l=lo;
        }
        if(ft.qry(j)>0){
            lo=0;
            hi=j-1;
            while(lo<hi){
                mid=(lo+hi+1)/2;
                if(ft.qry(j)-ft.qry(mid-1)>0) lo=mid;
                else hi=mid-1;
            }
            r=lo;
        }
        if(l==-1&&r==-1) pr[j]=-1;
        else if(l==-1) pr[j]=r;
        else if(r==-1) pr[j]=l;
        else{
            if(a[r]<a[l]) pr[j]=r;
            else pr[j]=l;
        }
        //cout<<l<<" "<<r<<" "<<j<<"\n";
        ft.upd(j,1);
    }
   }
   vector<vector<int>> adj;
   adj.resize(n);
   vector<vector<int>> dp(n,vector<int>(m+1));
   ll x=0;
   rep(i,0,n){
    if(pr[i]!=-1) adj[pr[i]].pb(i);
    else{
        x=i;
    }
   }
   //rep(i,0,n) cout<<pr[i]<<" ";
   dfs(x,adj,dp);
   //if(dp[x][m]==677569164) done(351025663);
   done(dp[x][m]);
   //351025663
}
signed main(){
   ios_base::sync_with_stdio(false);
   cin.tie(NULL);
   cout.tie(NULL);
   cout<<fixed<<setprecision(20);
   ll t = 1;
   cin >> t;
   while (t--)
       solve();
   return 0;
}*/

Answer: 2


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve()
{
    int n;
    cin >> n;
    vector<vector<int>> e(n);
    vector<int> deg(n);
    for (int i = 1;i < n;i++)
    {
        int v,u;
        cin >> v >> u;
        v--;
        u--;
        e[u].push_back(v);
        e[v].push_back(u);
        deg[u]++;
        deg[v]++;
    }
    sort(e.begin(),e.end(),[](vector<int> a,vector<int> b) {return a.size() > b.size();});
    int mx = e[0].size();
    int premx = -1;
    int cntmx = 0;
    int cntpremx = 0;
    for (int i = 0;i < n;i++)
    {
        if (e[i].size() == mx) cntmx++;
        if (i && e[i - 1].size() == mx && e[i].size() != mx) premx = e[i].size();
        if (e[i].size() == premx) cntpremx++;
    }
    int ans = 0;
    for (int i = 0;e[i].size() == mx;i++)
    {
        int curcntmx = 0;
        int curcntpremx = 0;
        for (auto& adj : e[i])
        {
            if (deg[adj] == mx) curcntmx++;
            else if (deg[adj] == premx) curcntpremx++;
        }
        if (cntmx - curcntmx - 1 > 0) ans = max(ans,mx * 2 - 1);
        else if (cntpremx - curcntpremx > 0) ans = max(ans,mx + premx - 1);
        if (i != 0) ans = max(ans,mx * 2 - 2);
        else ans = max(ans,mx + premx - 2);
    }
    cout << ans << '\n';
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
	int t;
	cin >> t;
	while(t--) solve();
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve()
{
    int n;
    cin >> n;
    vector<vector<int>> e(n);
    vector<int> deg(n);
    for (int i = 1;i < n;i++)
    {
        int v,u;
        cin >> v >> u;
        v--;
        u--;
        e[u].push_back(v);
        e[v].push_back(u);
        deg[u]++;
        deg[v]++;
    }
    sort(e.begin(),e.end(),[](vector<int> a,vector<int> b) {return a.size() > b.size();});
    int mx = e[0].size();
    int premx = -1;
    int cntmx = 0;
    int cntpremx = 0;
    for (int i = 0;i < n;i++)
    {
        if (e[i].size() == mx) cntmx++;
        if (i && e[i - 1].size() == mx && e[i].size() != mx) premx = e[i].size();
        if (e[i].size() == premx) cntpremx++;
    }
    int ans = 0;
    for (int i = 0; i < n &&  e[i].size() == mx;i++)
    {
        int curcntmx = 0;
        int curcntpremx = 0;
        for (auto& adj : e[i])
        {
            if (deg[adj] == mx) curcntmx++;
            else if (deg[adj] == premx) curcntpremx++;
        }
        if (cntmx - curcntmx - 1 > 0) ans = max(ans,mx * 2 - 1);
        else if (cntpremx - curcntpremx > 0) ans = max(ans,mx + premx - 1);
        else if (i != 0) ans = max(ans,mx * 2 - 2);
        else ans = max(ans,mx + premx - 2);
    }
    cout << ans << '\n';
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
	int t;
	cin >> t;
	while(t--) solve();
	return 0;
}

Answer: 1


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

#define int long long
//
#define pb push_back
#define ppb pop_back
#define pii pair<int,int>
#define vi  vector<int>
#define all(v) v.begin(),v.end()
#define ff first
#define ss second
#define vvi(v,n,m,k) vector<vi>v(n,vi(m,k));
#define endl "\n"
#define MOD 998244353
#define print(v) for(int i=0;i<v.size();i++){cout<<v[i]<<" ";} cout<<endl;
#define printl(v) for(auto it :v){cout<<it<<endl;}
#define printp(v) for(auto it : v){cout<<it.ff<<" "<<it.ss<<endl;}
#define printvv(v) {for(int i=0;i<v.size();i++){print(v[i]);}}
//
#define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL)

void solve(){
    int n;
    cin>>n;
    vector<vi>adj(n);
    for(int i=0;i<n-1;i++){
        int x,y;
        cin>>x>>y;
        x--;
        y--;
        adj[x].pb(y);
        adj[y].pb(x);
    }
    vector<pii>v;
    vi incoming(n,0);
    for(int i=0;i<n;i++){
        incoming[i]=adj[i].size();
        v.pb({adj[i].size(),i});
    }
    sort(all(v));
    int cnt=v[n-1].ff;
    int node=v[n-1].ss;
    incoming[node]=0;
    for(int i=0;i<adj[node].size();i++){
        int ver=adj[node][i];
        incoming[ver]=adj[ver].size()-1;
    }
    sort(all(incoming));
    cnt+=incoming[n-1]-1;
    cout<<min(cnt,n-2)<<endl;
}

signed main(){
    fastio();
    int t = 1;
    cin >> t;
    while(t--){
        solve();
    }
}

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

#define int long long
//
#define pb push_back
#define ppb pop_back
#define pii pair<int,int>
#define vi  vector<int>
#define all(v) v.begin(),v.end()
#define ff first
#define ss second
#define vvi(v,n,m,k) vector<vi>v(n,vi(m,k));
#define endl "\n"
#define MOD 998244353
#define print(v) for(int i=0;i<v.size();i++){cout<<v[i]<<" ";} cout<<endl;
#define printl(v) for(auto it :v){cout<<it<<endl;}
#define printp(v) for(auto it : v){cout<<it.ff<<" "<<it.ss<<endl;}
#define printvv(v) {for(int i=0;i<v.size();i++){print(v[i]);}}
//
#define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL)

void solve(){
    int n;
    cin>>n;
    vector<vi>adj(n);
    for(int i=0;i<n-1;i++){
        int x,y;
        cin>>x>>y;
        x--;
        y--;
        adj[x].pb(y);
        adj[y].pb(x);
    }
    vector<pii>v;
    vi incoming(n,0);
    for(int i=0;i<n;i++){
        incoming[i]=adj[i].size();
        v.pb({incoming[i],i});
    }
    sort(all(v));
    int cnt=v[n-1].ff;
    int node=v[n-1].ss;
    incoming[node]=-1;
    for(int i=0;i<adj[node].size();i++){
        int ver=adj[node][i];
        incoming[ver]--;
    }
    sort(all(incoming));
    cnt+=incoming[n-1]-1;
    int maxi=cnt;
    for(int i=0;i<n;i++){
        incoming[i]=adj[i].size();
    }
    cnt=v[n-2].ff;
    node=v[n-2].ss;
    incoming[node]=-1;
    for(int i=0;i<adj[node].size();i++){
        int ver=adj[node][i];
        incoming[ver]--;
    }
    sort(all(incoming));
    cnt+=incoming[n-1]-1;
    cout<<max(cnt,maxi)<<endl;
}

signed main(){
    fastio();
    int t = 1;
    cin >> t;
    while(t--){
        solve();
    }
}

Answer: 2


"""
For God so loved the world that he gave his one and only Son,
that whoever believes in him shall not perish but have eternal life.
JOHN 3:16
"""
import random
from math import *
from functools import lru_cache
from itertools import accumulate
from fractions import Fraction
from bisect import bisect_left as bl
from bisect import bisect_right as br
from operator import itemgetter
from collections import Counter,deque,defaultdict
from heapq import heappop as hpop, heappush as hpush
# constants
p = 10**9 + 7
ANS = ['NO','YES']
import sys
input = sys.stdin.readline
output = sys.stdout.write
#sys.setrecursionlimit(110000)
# #For large input
# input = sys.stdin.read
# data = input().split()
# Shortcut for input()
def I(): return int(input())
def S(): return input().strip()
def F(): return float(input())
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LS(): return list(map(str, input().split()))
def LF(): return list(map(float , input().split()))
# Shortcut for output()
res = []
def OI(res): output("\n".join(res))
def OL(res): output("\n".join(" ".join(i) for i in res))

t = I()
for _ in range(t):
    n = I()
    deg = [0]*(n+1)
    g = [[] for _ in range(n+1)]
    for _ in range(n-1):
        u,v = MI()
        deg[u] += 1
        deg[v]+=1
        g[u].append(v)
        g[v].append(u)
    m = max(deg)
    if deg.count(m) >= 3:
        print(2*m-1)
        continue
    ans = m
    node = deg.index(m)
    deg[node] = 0
    for child in g[node]:deg[child]-=1
    ans += (max(deg) - 1)
    print(ans)

"""
For God so loved the world that he gave his one and only Son,
that whoever believes in him shall not perish but have eternal life.
JOHN 3:16
"""
import random
from math import *
from functools import lru_cache
from itertools import accumulate
from fractions import Fraction
from bisect import bisect_left as bl
from bisect import bisect_right as br
from operator import itemgetter
from collections import Counter,deque,defaultdict
from heapq import heappop as hpop, heappush as hpush
# constants
p = 10**9 + 7
ANS = ['NO','YES']
import sys
input = sys.stdin.readline
output = sys.stdout.write
#sys.setrecursionlimit(110000)
# #For large input
# input = sys.stdin.read
# data = input().split()
# Shortcut for input()
def I(): return int(input())
def S(): return input().strip()
def F(): return float(input())
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LS(): return list(map(str, input().split()))
def LF(): return list(map(float , input().split()))
# Shortcut for output()
res = []
def OI(res): output("\n".join(res))
def OL(res): output("\n".join(" ".join(i) for i in res))

t = I()
while t:
    n = I()
    deg = [0]*n
    g = defaultdict(set)
    for _ in range(n-1):
        u,v = MI()
        g[u-1].add(v-1)
        g[v-1].add(u-1)
        deg[u-1]+=1
        deg[v-1]+=1
    ans = 0
    #when nodes are adjacent
    for node in g:
        for child in g[node]:
            ans = max(ans,deg[node] + deg[child]-2)
    #when two nodes are not adjacent
    s = sorted([(deg[i],i) for i in range(n)],reverse = 1)
    for _,node1 in s:
        for _,node2 in s:
            if node1 == node2 or node1 in g[node2]: continue
            ans = max(ans, deg[node1] + deg[node2] - 1)
            break
    print(ans)
    t-=1

Answer: 1


#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 998244353;

void solve()
{
	int n;
	cin>>n;

	vector<int> subTreeMax(n+1,0);
	vector<int> tree[n+1];

	for(int i = 0; i < n-1; ++i) {
		int u,v;
		cin>>u>>v;

		tree[u].push_back(v);
		tree[v].push_back(u);
	}

	int res = 0;

	function<void(int,int)> dfs = [&](int node, int parent) {
		for(auto child : tree[node]) {
			if(child == parent) continue;
			dfs(child,node);
			subTreeMax[node] = max(subTreeMax[node], (int)tree[child].size());
			subTreeMax[node] = max(subTreeMax[node], subTreeMax[child]);
		}
	};

	function<void(int,int)> dfs2 = [&](int node, int parent) {
		for(auto child : tree[node]) {
			if(child == parent) continue;
			res = max(res,(int)tree[child].size() + (int)tree[node].size() - 2ll);
			res = max(res,(int)tree[node].size() + subTreeMax[child] - 1);
			dfs(child,node);
		}
	};

	dfs(1,-1);
	dfs2(1,-1);

	// for(int i = 1; i <= n; ++i) {
	// 	cout<<subTreeMax[i]<<" ";
	// }
	// cout<<endl;

	cout<<res<<endl;
}

int32_t main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int tc;
	cin >> tc;
	while (tc--)
	{
		solve();
	}
	return 0;
}

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 998244353;

void solve()
{
	int n;
	cin>>n;

	vector<int>tree[n+1];
	vector<int> degree(n+1);

	for(int i = 1; i < n; ++i) {
		int u,v;
		cin>>u>>v;

		tree[u].push_back(v);
		tree[v].push_back(u);

		degree[u]++;
		degree[v]++;
	}

	vector<int> sorted_degree = degree;
	sort(sorted_degree.begin(),sorted_degree.end());

	int res = 1;
	int ans = 0;

	for(int first_node = 1; first_node <= n; ++first_node) {
		res = degree[first_node];

		vector<int> near_nodes;
		near_nodes.push_back(degree[first_node]);

		for(auto child : tree[first_node]) {
			near_nodes.push_back(degree[child]);
		}

		sort(near_nodes.rbegin(),near_nodes.rend());

		vector<int> rem;
		int mx = -1;

		for(auto deg : near_nodes) {
			if(deg == sorted_degree[(int)sorted_degree.size() - 1]){
				sorted_degree.pop_back();
				rem.push_back(deg);
			}
		}

		if(sorted_degree.size()) {
			mx = max(mx, sorted_degree[(int)sorted_degree.size() - 1]);
		}

		for(auto child : tree[first_node]) {
			mx = max(mx, degree[child] - 1);
		}

		reverse(rem.begin(),rem.end());

		for(auto it : rem) {
			sorted_degree.push_back(it);
		}

		ans = max(ans, res + mx - 1);
	}

	cout<<ans<<endl;

}

int32_t main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int tc;
	cin >> tc;
	while (tc--)
	{
		solve();
	}
	return 0;
}

Answer: 2


// Author //

// Md Nehal //

#include<bits/stdc++.h>

using namespace std;

void solve(){
	int n;
	cin>>n;
	int arr[n+10];
	for(int i=0;i<=n+6;++i){
		arr[i] =0;
	}
	vector<int>graph[n+10];
	for(int i=1;i<n;++i){
		int u ,v;
		cin>>u>>v;
		graph[v].push_back(u);
		graph[u].push_back(v);
		arr[u]++,arr[v]++;
	}
	int maxi =0;
	for(int i=1;i<=n;++i){
		maxi = max(arr[i],maxi);
	}
	int cnt =0;
	for(int i=1;i<=n;++i){
		if(arr[i] == maxi){
			cnt++;
		}
	}
	if(cnt>2){
		cout<<maxi*2 - 1<<endl;
		return ;
	}
	int result =maxi,ind=0;
	for(int i=1;i<=n;++i){
		if(arr[i] == maxi){
			ind = i;
			for(auto &child:graph[i]){
				arr[child]--;
			}
			break ;
		}
	}
	maxi =0;
	for(int i=1;i<=n;++i){
		if(i == ind){
			continue;
		}
		maxi = max(maxi,arr[i]);
	}
	cout<<result+maxi-1<<endl;
	return ;
}
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t;
	cin>>t;
	while(t--){
		solve();
	}
	return 0;
}

// Author //

// Md Nehal //

#include<bits/stdc++.h>

using namespace std;

void solve(){
	int n;
	cin>>n;
	int arr[n+10];
	for(int i=0;i<=n+6;++i){
		arr[i] =0;
	}
	vector<int>graph[n+10];
	for(int i=1;i<n;++i){
		int u ,v;
		cin>>u>>v;
		graph[v].push_back(u);
		graph[u].push_back(v);
		arr[u]++,arr[v]++;
	}
	int maxi =0;
	for(int i=1;i<=n;++i){
		maxi = max(arr[i],maxi);
	}
	int result =maxi,ind=0;
	for(int i=1;i<=n;++i){
		if(arr[i] == maxi){
			ind = i;
			for(auto &child:graph[i]){
				arr[child]--;
			}
			break ;
		}
	}
	maxi =0;
	for(int i=1;i<=n;++i){
		if(i == ind){
			continue;
		}
		maxi = max(maxi,arr[i]);
	}
	cout<<result+maxi-1<<endl;
	return ;
}
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t;
	cin>>t;
	while(t--){
		solve();
	}
	return 0;
}

Answer: 1


#include <bits/stdc++.h>
#define ll int64_t
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        set<pair<int, int>> edges;
        vector<int> indegree(n + 1, 0);
        for (int i = 0; i < n - 1; i++)
        {
            int first, second;
            cin >> first >> second;
            indegree[first]++;
            indegree[second]++;
            edges.insert({first, second});
            edges.insert({second, first});
        }
        vector<pair<int, int>> degree;
        for (int i = 1; i <= n; i++)
        {
            degree.push_back({indegree[i], i});
        }
        sort(degree.rbegin(), degree.rend());

        int res = 0;
        // first we will do for non adjacent
        for (int i = 0; i < n; i++)
        {
            int degree1 = degree[i].first;
            int ele1 = degree[i].second;
            for (int j = i + 1; j < n; j++)
            {
                int degree2 = degree[j].first;
                int ele2 = degree[j].second;
                if (edges.count({ele1, ele2}))
                    continue;
                else
                {
                    res = max(res, degree1 + degree2 - 1);
                    break;
                }
            }
        }
        // now we will do for adjacent elements
        for (auto a : edges)
        {
            int first = a.first;
            int second = a.second;
            int degree1 = indegree[first];
            int degree2 = indegree[second];
            res = max(res, degree1 + degree2 - 2);
        }
        cout << res << endl;
    }

    return 0;
}

#include <bits/stdc++.h>
#define ll int64_t
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;

        vector<unordered_set<int>> adj(n + 1);
        for (int i = 0; i < n - 1; i++)
        {
            int first, second;
            cin >> first >> second;
            adj[first].insert(second);
            adj[second].insert(first);
        }
        int maxi = 0, index = 0;

        for (int i = 1; i <= n; i++)
        {
            int key = i;
            unordered_set<int> &neighbors = adj[i];
            if (neighbors.size() > maxi)
            {
                maxi = neighbors.size();
                index = key;
            }
        }
        unordered_set<int> &byebye = adj[index];
        // cout << index << endl;
        for (auto a : byebye)
        {
            int currele = a;
            adj[currele].erase(index);
        }
        byebye.clear();
        byebye.insert(-1);

        maxi = -1, index = 0;

        for (int i = 1; i <= n; i++)
        {
            int key = i;
            unordered_set<int> &neighbors = adj[i];
            if (neighbors.count(-1))
            {
                // cout << i << endl;
                continue;
            }

            if ((int)neighbors.size() > maxi)
            {

                maxi = neighbors.size();
                index = i;
            }
        }

        unordered_set<int> &byebye2 = adj[index];
        // cout << index << endl;
        for (auto a : byebye2)
        {
            int currele = a;
            adj[currele].erase(index);
        }
        byebye2.clear();
        byebye2.insert(-1);
        int res = 0;
        unordered_set<int> selected;
        for (int i = 1; i <= n; i++)
        {
            unordered_set<int> &neighbors = adj[i];
            if (neighbors.count(-1) || selected.count(i))
                continue;
            selected.insert(i);
            for (auto a : neighbors)
            {
                selected.insert(a);
            }
            res++;
        }
        cout << res << endl;
    }
    return 0;
}

Answer: 1


#include<bits/stdc++.h>
using namespace std;
#define fi first
#define sec second

void solve(){
	int n;
	cin>>n;

	vector<int> adj[n+2];

	for(int i=0; i<n-1; i++){
		int u,v;
		cin>>u>>v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}

	vector<int> ch(n+2);
	vector<pair<int,int>> x;

	for(int i=1; i<=n; i++){
		x.push_back({adj[i].size(), i});
	}

	sort(x.begin(), x.end());
	reverse(x.begin(), x.end());

	if(x[0].fi == 1){
		cout<<"0\n";
		return;
	}

	for(auto k : adj[x[0].sec]){
		ch[k] = 1;
	}
	int ans = x[0].fi;
	int mx = -2;

	for(int i=1; i<n; i++){
		if(ch[x[i].sec] == 0){
			mx = max(mx, x[i].fi - 1);
			continue;
		}

		if(x[i].fi == 1){
			mx = max(mx, -1);
		}else{
			mx = max(mx, x[i].fi - 2);
		}
	}

	cout<<ans+mx<<"\n";

	return;
}

int main(){

	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int t;
	cin>>t;
	while(t--){
		solve();
	}

	return 0;
}

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

#define fi first
#define sec second
#define ll long long

void solve(){
	ll n;
	cin>>n;

	vector<ll> adj[n+2];

	for(ll i=0; i<n-1; i++){
		ll u,v;
		cin>>u>>v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}

	vector<pair<ll,ll>> x;

	for(ll i=1; i<=n; i++){
		x.push_back({adj[i].size(), i});
	}

	sort(x.begin(), x.end());
	reverse(x.begin(), x.end());

	if(x[0].fi == 1){
		cout<<"0\n";
		return;
	}

	ll real_ans = 0;
	for(ll j=0; j<min(n, 5LL); j++){
		vector<ll> ch(n+2);
		for(auto k : adj[x[j].sec]){
			ch[k] = 1;
		}

		ll ans = x[j].fi;
		ll mx = -2;

		for(ll i=j+1; i<n; i++){
			if(i == j)continue;
			if(ch[x[i].sec] == 0){
				mx = max(mx, x[i].fi - 1);
				continue;
			}

			if(x[i].fi == 1){
				mx = max(mx, -1LL);
			}else{
				mx = max(mx, x[i].fi - 2);
			}
		}

		real_ans = max(ans+mx, real_ans);
//		cout<<ans+mx<<"\n";
	}

	cout<<real_ans<<"\n";

	return;
}

int main(){

	ios_base::sync_with_stdio(false);
	cin.tie(0);

	ll t;
	cin>>t;
	while(t--){
		solve();
	}

	return 0;
}

Answer: 2


#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;

const int inf = INT_MAX;
const int mod = 998244353;

void solve() {
    int n; cin >> n;
    vector<vector<int>> adj(n + 1);
    vector<int> deg(n + 1);
    vector<int> mx(n + 1), dp(n + 1);
    for (int i = 1, u, v;i < n;i++) {
        cin >> u >> v;
        adj[u].emplace_back(v);
        adj[v].emplace_back(u);
        deg[u] += 1, deg[v] += 1;
    }
    auto dfs = [&](auto &&self, int u, int pre) -> void {
        vector<int> degs;
        for (auto &v : adj[u]) {
            if (v == pre) continue;
            self(self, v, u);
            degs.emplace_back(deg[v]);
            dp[u] = max(dp[u], dp[v]);
            dp[u] = max(deg[u] + deg[v] - 2, dp[u]);
            dp[u] = max(dp[u], deg[u] + mx[v] - 1);
            mx[u] = max({mx[u], mx[v], deg[v]});
        }
        sort(degs.begin(), degs.end(), greater<int>());
        if (degs.size() >= 2)
            dp[u] = max(dp[u], degs[0] + degs[1] - 1);
    };
    dfs(dfs, 1, 0);
    cout << dp[1] << endl;
}

signed main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int T = 1; cin >> T;
    while (T--) solve();
    return 0;
}

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;

const int inf = INT_MAX;
const int mod = 998244353;

void solve() {
    int n; cin >> n;
    vector<vector<int>> adj(n + 1);
    vector<int> deg(n + 1);
    vector<int> mx(n + 1), dp(n + 1);
    for (int i = 1, u, v;i < n;i++) {
        cin >> u >> v;
        adj[u].emplace_back(v);
        adj[v].emplace_back(u);
        deg[u] += 1, deg[v] += 1;
    }
    auto dfs = [&](auto &&self, int u, int pre) -> void {
        int maxdeg = 0, maxdeg2 = 0;
        for (auto &v : adj[u]) {
            if (v == pre) continue;
            self(self, v, u);
            dp[u] = max(dp[u], dp[v]);
            dp[u] = max(deg[u] + deg[v] - 2, dp[u]);
            dp[u] = max(dp[u], deg[u] + mx[v] - 1);
            dp[u] = max(dp[u], deg[v] + maxdeg - 1);
            dp[u] = max(dp[u], maxdeg2 + deg[v] - 1);
            dp[u] = max(dp[u], mx[v] + maxdeg - 1);
            dp[u] = max(dp[u], mx[v] + maxdeg2 - 1);
            mx[u] = max({mx[u], mx[v], deg[v]});
            maxdeg2 = max(maxdeg2, mx[u]);
            maxdeg = max(maxdeg, deg[v]);
        }
    };
    dfs(dfs, 1, 0);
    cout << dp[1] << endl;
}

signed main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int T = 1; cin >> T;
    while (T--) solve();
    return 0;
}

Answer: 2


#include <iostream>
#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#include <set>
#include <map>

using namespace std;

#define endl "\n"
#define ll long long
#define dl double long
#define pb push_back
const int mod = 998244353;

void solve() {

    int n;
    cin >> n;

    unordered_set<int> adj[n+1];
    vector<pair<int,int>> edges;

    for(int i=1; i<n; i++) {
        int u, v;
        cin >> u >> v;
        edges.pb({u,v});

        adj[u].insert(v);
        adj[v].insert(u);
    }

    int ans = 0;

    for(auto& it: edges) {
        int eu = adj[it.first].size();
        int ev = adj[it.second].size();

        ans = max(ans, eu+ev-2);
    }

    vector<pair<int,int>> numOfAdjEdges(n+1);
    numOfAdjEdges[0] = {0,0};

    for(int i=1; i<=n; i++) {
        numOfAdjEdges[i] = {-adj[i].size(), i};
    }

    sort(numOfAdjEdges.begin(), numOfAdjEdges.end());

    for(int j=0; j<n; j++) {
        int v1 = numOfAdjEdges[j].second;
        int e1 = -numOfAdjEdges[j].first;

        for(int i=j+1; i<n; i++) {
            int v2 = numOfAdjEdges[i].second;
            if(adj[v1].find(v2) != adj[v1].end()) continue;

            int e2 = -numOfAdjEdges[i].first;
            ans = max(ans, e1+e2-1);
            break;
        }
    }

    cout << ans << endl;

}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int testCases;
    cin >> testCases;

    while(testCases--) solve();
    return 0;
}

#include <iostream>
#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#include <set>
#include <map>

using namespace std;

#define endl "\n"
#define ll long long
#define dl double long
#define pb push_back
const int mod = 998244353;

int getVertex(int& n, unordered_set<int> adj[]) {

}

void solve() {

    int n;
    cin >> n;

    unordered_set<int> adj[n+1];

    for(int i=1; i<n; i++) {
        int u, v;
        cin >> u >> v;

        adj[u].insert(v);
        adj[v].insert(u);
    }

    vector<pair<int,int>> numOfAdjEdges(n+1);
    numOfAdjEdges[0] = {0,0};

    for(int i=1; i<=n; i++) {
        numOfAdjEdges[i] = {-adj[i].size(), i};
    }

    sort(numOfAdjEdges.begin(), numOfAdjEdges.end());
    // for(int i=0; i<n; i++) {
    //     cout << -numOfAdjEdges[i].first << ", " << numOfAdjEdges[i].second << endl;
    // }

    int len = 0;
    while(len < n && numOfAdjEdges[len].first == numOfAdjEdges[0].first) len++;

    // cout << len << endl;

    if(len == 1) {
        int ans = 0;
        int e1 = -numOfAdjEdges[0].first, v1 = numOfAdjEdges[0].second;
        // cout << v1 << " : " << e1 << endl;

        for(int i=1; i<n; i++) {
            int e2 = -numOfAdjEdges[i].first;
            int v2 = numOfAdjEdges[i].second;

            // cout << v2 << " : " << e2 << endl;

            if(e2 != -numOfAdjEdges[1].first) break;

            int comps = e1+e2-1;
            if(adj[v1].find(v2) != adj[v1].end()) comps--;

            ans = max(ans, comps);
        }

        cout << ans << endl;
    }
    else {
        int ans = 0;
        int e1 = -numOfAdjEdges[0].first, v1 = numOfAdjEdges[0].second;
        // cout << v1 << " : " << e1 << endl;

        for(int i=1; i<len; i++) {
            int e2 = -numOfAdjEdges[i].first;
            int v2 = numOfAdjEdges[i].second;

            // cout << v2 << " : " << e2 << endl;

            int comps = e1+e2-1;
            if(adj[v1].find(v2) != adj[v1].end()) comps--;

            ans = max(ans, comps);
        }

        cout << ans << endl;
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int testCases;
    cin >> testCases;

    while(testCases--) solve();
    return 0;
}

Answer: 1


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

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int,null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>

#define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
#define int long long int
#define dec greater<pair<int,int>>()
#define all(x) (x).begin(), (x).end()
#define mod 1000000007
bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) { return (a.second < b.second); }

void solve()
{
    int n;
    cin>>n;
    vector<int> in_degree(n + 1);
    map<pair<int,int>,int>mp;
    for(int i=0; i<n-1; i++)
    {
        int u,v;
        cin>>u>>v;
        in_degree[u]++;
        in_degree[v]++;
        mp[{u,v}]++;
        mp[{v,u}]++;
    }
    vector<pair<int,int>>vp;
    for(int i=1; i<=n; i++){
        vp.push_back({in_degree[i],i});
    }
    sort(all(vp),dec);
    //for(auto &[x,y] : vp)cout<<x<<' '<<y<<'\n';
    int res=0;
    for(int i=0; i<vp.size(); i++)
    {
        for(int j=i+1; j<vp.size(); j++)
        {
            if(!mp.count({vp[i].second,vp[j].second}))res=max(res,vp[i].first+vp[j].first-1);
        }
    }

    for(auto ii : mp)
    {
        int x=ii.first.first,y=ii.first.second;
        res=max(res,in_degree[x]+in_degree[y]-2);
    }
    cout<<res<<'\n';
}

signed main()
{
    fast;
    int t=1;
    cin>>t;
    while(t--)
      solve();
}

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

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int,null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>

#define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
#define int long long int
#define dec greater<pair<int,int>>()
#define all(x) (x).begin(), (x).end()
#define mod 1000000007
bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) { return (a.second < b.second); }

void solve()
{
    int n;
    cin>>n;
    vector<int> in_degree(n + 1);
    map<pair<int,int>,int>mp;
    for(int i=0; i<n-1; i++)
    {
        int u,v;
        cin>>u>>v;
        in_degree[u]++;
        in_degree[v]++;
        mp[{u,v}]++;
        mp[{v,u}]++;
    }
    vector<pair<int,int>>vp;
    for(int i=1; i<=n; i++){
        vp.push_back({in_degree[i],i});
    }
    sort(all(vp),dec);
    //for(auto &[x,y] : vp)cout<<x<<' '<<y<<'\n';
    int res=0;
    for(int i=0; i<vp.size(); i++)
    {
        for(int j=i+1; j<vp.size(); j++)
        {
            if(!mp.count({vp[i].second,vp[j].second})){
                res = max(res, vp[i].first + vp[j].first - 1);
                break;
            }
        }
    }

    for(auto ii : mp)
    {
        int x=ii.first.first,y=ii.first.second;
        res=max(res,in_degree[x]+in_degree[y]-2);
    }
    cout<<res<<'\n';
}

signed main()
{
    fast;
    int t=1;
    cin>>t;
    while(t--)
      solve();
}

Answer: 2


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

#define fr(i,s,e) for(ll i=s ; i<e ; i++)
#define rf(i,s,e) for(ll i=s ; i>=e ; i--)
#define ff first
#define ss second
#define pb push_back
typedef long long ll;
typedef vector<ll> vll;

ll MOD=998244353;

ll fastpow(ll base , ll power){
	ll ans=1;
	while(power>0){
		if(power&1){
			ans*=base;
			ans%=MOD;
		}
		power>>=1;
		base*=base;
		base%=MOD;
	}
	return ans;
}

void solve(){
	ll n;
	cin >> n;
	vector<vll> v(n);
	vll si(n);
	fr(i, 0, n-1){
		ll a, b;
		cin >> a >> b;
		si[--a]++;
		si[--b]++;
		v[a].pb(b);
		v[b].pb(a);
	}
	sort(si.begin(), si.end());
	ll cnt = 0, k=0;
	fr(i, 0 , n) if(si[n-2] == v[i].size()) cnt++;
	fr(i, 0 , n){
		if(si[n-1] == v[i].size()){
			ll c = 0;
			for(auto x : v[i]){
				if(v[x].size() == si[n-2]) c++;
			}
			if(c == cnt) k = 1;
			if(si[n-1] == si[n-2] && c != cnt-1) k=-1;
		}
	}
	cout << si[n-1] + si[n-2] - 1 - (si[n-1]==si[n-2]) - k << endl;

}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr); cout.tie(nullptr);
	ll tt=1;
	cin >> tt;
	while(tt--){
		solve();
	}
}

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

#define fr(i,s,e) for(ll i=s ; i<e ; i++)
#define rf(i,s,e) for(ll i=s ; i>=e ; i--)
#define ff first
#define ss second
#define pb push_back
typedef long long ll;
typedef vector<ll> vll;

ll MOD=998244353;

ll fastpow(ll base , ll power){
	ll ans=1;
	while(power>0){
		if(power&1){
			ans*=base;
			ans%=MOD;
		}
		power>>=1;
		base*=base;
		base%=MOD;
	}
	return ans;
}

void solve(){
	ll n;
	cin >> n;
	vector<vll> v(n+1);
	vll used(n+1);
	fr(i, 1, n+1) v[i].pb(i);
	fr(i, 0, n-1){
		ll a,b;
		cin >> a >> b;
		v[a].pb(b);
		v[b].pb(a);
	}
	vector<vll> v1(v.begin(), v.end());
	sort(v.begin(), v.end(), [](vll a, vll b){return a.size() < b.size();});
	fr(i, 1, v[n].size()){
		v1[v[n][i]].erase( find(v1[v[n][i]].begin(), v1[v[n][i]].end(), v[n][0]) );
	}
	v1.erase(v1.begin() + v[n][0]);
	vector<vll> v2(v1.begin(), v1.end());
	sort(v1.begin(), v1.end(), [](vll a, vll b){return a.size() < b.size();});
	fr(i, 1, v1[n-1].size()){
		fr(j, 1, v2.size()){
			if(v2[j][0] == v1[n-1][i]) v2[j].erase( find(v2[j].begin(), v2[j].end(), v1[n-1][0]) );
		}
	}
	fr(j, 1, v2.size()){
		if(v2[j][0] == v1[n-1][0]) v2.erase( v2.begin() + j);
	}
	if(v2.size()==1){cout << "0\n"; return;}
	ll cnt = 0;
	fr(i, 1, v2.size()){
		if( !used[v2[i][0]] ){
			cnt++;
			for(auto x : v2[i]) used[x] = 1;;
		}
	}
	cout << cnt << endl;
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr); cout.tie(nullptr);
	ll tt=1;
	cin >> tt;
	while(tt--){
		solve();
	}
}

Answer: 1


#include <bits/stdc++.h>
using namespace std;
#define ll long long

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    ll T;
    cin >> T;
    while(T--) {
        ll n;
        cin >> n;
        vector<set<ll>> adj(n);
        vector<ll> deg(n);
        for(ll i = 0; i < n - 1; i++) {
            ll u, v;
            cin >> u >> v;
            u--;
            v--;
            adj[u].insert(v);
            adj[v].insert(u);
            deg[u]++;
            deg[v]++;
        }
        vector<pair<ll, ll>> e;
        for(ll i = 0; i < n; i++) {
            e.push_back({deg[i], i});
        }
        sort(e.rbegin(), e.rend());
        ll ans = 0;
        for(ll i = 0; i < n; i++) {
            for(ll j = i + 1; j < n; j++) {
                ll u = e[i].second;
                ll v = e[j].second;
                if(adj[u].count(v)) {
                    continue;
                }
                ans = max(ans, deg[u] + deg[v] - 1);
                break;
            }
        }
        for(ll i = 0; i < n; i++) {
            for(ll j: adj[i]) {
                ans = max(ans, deg[i] + deg[j] - 2);
            }
        }
        cout << ans << '\n';
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    ll T;
    cin >> T;
    while(T--) {
        ll n;
        cin >> n;
        vector<set<ll>> adj(n);
        vector<ll> deg(n);
        for(ll i = 0; i < n - 1; i++) {
            ll u, v;
            cin >> u >> v;
            u--;
            v--;
            adj[u].insert(v);
            adj[v].insert(u);
            deg[u]++;
            deg[v]++;
        }
        vector<pair<ll, ll>> e;
        for(ll i = 0; i < n; i++) {
            e.push_back({deg[i], i});
        }
        sort(e.rbegin(), e.rend());
        ll ans = 0;
        for(ll i = 0; i < n; i++) {
            for(ll j = i + 1; j < n; j++) {
                ll u = e[i].second;
                ll v = e[j].second;
                if(adj[u].count(v)) {
                    continue;
                }
                ans = max(ans, deg[u] + deg[v] - 1);
            }
        }
        for(ll i = 0; i < n; i++) {
            for(ll j: adj[i]) {
                ans = max(ans, deg[i] + deg[j] - 2);
            }
        }
        cout << ans << '\n';
    }
    return 0;
}

Answer: 1


// Problem: C. Remove Exactly Two
// Contest: Codeforces - Codeforces Round 1000 (Div. 2)
// URL: https://codeforces.com/contest/2063/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// Author: alchemist_17

#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define sped ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);

#define ln '\n'
#define ld long double
#define int long long
#define f first
#define s second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define mii map<int, int>
#define pii pair<int, int>
#define vi vector<int>
#define vpii vector<pii>
#define vvi vector<vi>
#define pb push_back
#define sara(x) cout << #x << " = " << x << "\n"
#define setbitsll(n)  __builtin_popcountll(n) //counts all set bits in (int)num, setbitsll(num)==1 i.e no. is power of 2
#define setbits(n)  __builtin_popcount(n)
#define msb(x) __builtin_clzll(x) // to count leading 0 , to find index = 64-msb(n)-1
#define lsb(x) __builtin_ctzll(x) // to count trailing 0 , to find index = lsb(n)
#define yesno(f) f?cout<<"YES\n":cout<<"NO\n"
#define mx(v) *max_element(v.begin(),v.end())
#define mn(v) *min_element(v.begin(),v.end())
#define loop(n) for(int i=0; i<n; ++i)
#define alone(v) v.erase(unique(v.begin(),v.end()),v.end())
#define inf LLONG_MAX
#define PI 3.14159265359
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>

/*
  If mod operations performed , divide won't work instead of / , * by its mod inverse
*/
/* ordered_set st
   st.order_of_key(k) : no. of elements < k
   *st.find_by_order(i) : value at index i (0-based)
*/
/* In Interactive problem use :
   endl (flushes buffer automatically)(provide o/p for each query)
   or use '\n' (provide o/p for all query at once) along with cout.flush();
*/

/* n=10010010
         0010(want till ith)
   extracted no.=(n%(1<<(i+1))) i.e.0010
   remaining no.=n^((n%(1<<(i+1)))) i.e. 10010000
   ct of ith → (i+1)*(n-i) // no. of subarrays containing the ith element, total subarrays = n*(n+1)/2
   n % 2ʲ -> last j bits of n
*/

// upper bound of factors:cbrt(n)

const long long M = 1000000007;
const int N = 1000000;
vector<bool> isprime(N + 1, true);
vector<int> spf(N + 1, 0);

int lcm(int a, int b){int g=__gcd(a, b); return a/g*b;}

int factorial(int n){n%=M; if(n<=1) return 1; return n*factorial(n-1)%M;}

int binexp(int a, int b , int m) {
  if (b == 0) return 1;
  if (b == 1) return (a) % m;
  int res = binexp(a, b / 2 , m);
  if (b % 2 == 0) return (res * res) % m;
  return ((res * res) % m * (a) % m) % m;
}

int modinv(int a, int p)
{return binexp(a, p - 2, p);}

long double ncr(int n,int r){if(n<r)return 0.0;if(n-r<r)r=n-r;long double ans=1.0;for(int i=1;i<=r;++i){ans*=n-i+1;ans/=i;}return ans;}

void SPF(){
  for (int i = 1; i <= N; i++){ spf[i] = i;}spf[1] = -1;
  for (int i = 2; i * i <= N; i++) {if (spf[i] == i) {for (int j = i * i; j <= N; j += i) {if (spf[j] == j) {spf[j] = i;}}}}
}

void sieve() {
    isprime[0]=isprime[1] = false;
for (int i = 2; i * i <= N; i++) {if (isprime[i]) {for (int j = i * i; j <= N; j += i) {if (isprime[j] == true) isprime[j] = false;}}}
}

//<---------------------------code begins--------------------------->

int32_t main() {
    sped
    int t;
    cin >> t;
    while (t--) {
         int n;
    cin>>n;
    vvi adj(n);
    for(int i=0;i<n-1;i++){
        int u,v;
        cin>>u>>v;
        --u;
        --v;
        adj[u].pb(v);
        adj[v].pb(u);
    }
    set<pii> s;
    vpii b;
    for(int i=0;i<n;i++){
        s.insert({adj[i].size(),i});
        b.pb({adj[i].size(),i});
    }
    sort(rall(b));
    int ans=0;
    for(int j=0;j<min(n,3ll);j++){
        int i=b[j].s;
        set<pii> temp=s;
        pii p1={adj[i].size(),i};
        int a1=max(0ll,p1.f);
        s.erase(s.find(p1));
        for(auto it:adj[i]){
            pii p1={adj[it].size(),it};
            s.erase(s.find(p1));
            pii p2={adj[it].size()-1,it};
            s.insert(p2);
        }
        auto it=(--s.end());
        int a2=max(0ll,it->f);
        ans=max(ans,a1+a2-1);
        s=temp;
    }
    cout << ans << ln;
    }
}

// Problem: C. Remove Exactly Two
// Contest: Codeforces - Codeforces Round 1000 (Div. 2)
// URL: https://codeforces.com/contest/2063/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// Author: alchemist_17

#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define sped ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);

#define ln '\n'
#define ld long double
#define int long long
#define f first
#define s second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define mii map<int, int>
#define pii pair<int, int>
#define vi vector<int>
#define vpii vector<pii>
#define vvi vector<vi>
#define pb push_back
#define sara(x) cout << #x << " = " << x << "\n"
#define setbitsll(n)  __builtin_popcountll(n) //counts all set bits in (int)num, setbitsll(num)==1 i.e no. is power of 2
#define setbits(n)  __builtin_popcount(n)
#define msb(x) __builtin_clzll(x) // to count leading 0 , to find index = 64-msb(n)-1
#define lsb(x) __builtin_ctzll(x) // to count trailing 0 , to find index = lsb(n)
#define yesno(f) f?cout<<"YES\n":cout<<"NO\n"
#define mx(v) *max_element(v.begin(),v.end())
#define mn(v) *min_element(v.begin(),v.end())
#define loop(n) for(int i=0; i<n; ++i)
#define alone(v) v.erase(unique(v.begin(),v.end()),v.end())
#define inf LLONG_MAX
#define PI 3.14159265359
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>

/*
  If mod operations performed , divide won't work instead of / , * by its mod inverse
*/
/* ordered_set st
   st.order_of_key(k) : no. of elements < k
   *st.find_by_order(i) : value at index i (0-based)
*/
/* In Interactive problem use :
   endl (flushes buffer automatically)(provide o/p for each query)
   or use '\n' (provide o/p for all query at once) along with cout.flush();
*/

/* n=10010010
         0010(want till ith)
   extracted no.=(n%(1<<(i+1))) i.e.0010
   remaining no.=n^((n%(1<<(i+1)))) i.e. 10010000
   ct of ith → (i+1)*(n-i) // no. of subarrays containing the ith element, total subarrays = n*(n+1)/2
   n % 2ʲ -> last j bits of n
*/

// upper bound of factors:cbrt(n)

const long long M = 1000000007;
const int N = 1000000;
vector<bool> isprime(N + 1, true);
vector<int> spf(N + 1, 0);

int lcm(int a, int b){int g=__gcd(a, b); return a/g*b;}

int factorial(int n){n%=M; if(n<=1) return 1; return n*factorial(n-1)%M;}

int binexp(int a, int b , int m) {
  if (b == 0) return 1;
  if (b == 1) return (a) % m;
  int res = binexp(a, b / 2 , m);
  if (b % 2 == 0) return (res * res) % m;
  return ((res * res) % m * (a) % m) % m;
}

int modinv(int a, int p)
{return binexp(a, p - 2, p);}

long double ncr(int n,int r){if(n<r)return 0.0;if(n-r<r)r=n-r;long double ans=1.0;for(int i=1;i<=r;++i){ans*=n-i+1;ans/=i;}return ans;}

void SPF(){
  for (int i = 1; i <= N; i++){ spf[i] = i;}spf[1] = -1;
  for (int i = 2; i * i <= N; i++) {if (spf[i] == i) {for (int j = i * i; j <= N; j += i) {if (spf[j] == j) {spf[j] = i;}}}}
}

void sieve() {
    isprime[0]=isprime[1] = false;
for (int i = 2; i * i <= N; i++) {if (isprime[i]) {for (int j = i * i; j <= N; j += i) {if (isprime[j] == true) isprime[j] = false;}}}
}

//<---------------------------code begins--------------------------->

int32_t main(){
    //sieve();
    // SPF();
    sped
    int t;
   	cin>>t;
    while(t--){
    	int n;cin>>n;
    	vector<vector<int>> adj(n+1);
    	for(int i=1;i<=n-1;++i){
    		int u,v;cin>>u>>v;
    		adj[u].pb(v);
    		adj[v].pb(u);
    	}
    	int ans=0;
    	set<pair<int,int>> st;
    	for(int i=1;i<=n;++i){
    		st.insert({adj[i].size(),i});
    	}
    	for(int i=1;i<=n;++i){
    		pii p={adj[i].size(),i};
    		set<pii> temp = st;
    		int a1=adj[i].size();
    		temp.erase(p);
    		for(auto x:adj[i]){
    			pii p1={adj[x].size(),x};
    			temp.erase(temp.find(p1));
    			pii p2={adj[x].size()-1,x};
    			temp.insert(p2);
    		}
    		if (!temp.empty()) {
                auto x = *prev(temp.end());
                int a2 = x.first;
                ans = max(ans, a1 + a2 - 1);
            }
    	}
    	cout<<ans<<'\n';
    }
}

Answer: 1


#include<stdio.h>
#include<set>
struct edge
{
	int to,next;
}e[400010];
int head[200010];
int sum;
void add(int from,int to)
{
	e[++sum].to=to;
	e[sum].next=head[from];
	head[from]=sum;
}
int size[200010];
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int n;
		sum=0;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			size[i]=0;
			head[i]=0;
		}
		for(int i=1;i<n;i++)
		{
			int u,v;
			scanf("%d%d",&u,&v);
			add(u,v);
			add(v,u);
			size[u]++;
			size[v]++;
		}
		std::multiset<int> mul;
		for(int i=1;i<=n;i++)
			mul.insert(size[i]);
		int maxn=0;
		for(int i=1;i<=n;i++)
		{
			int sze=size[i];
			mul.erase(size[i]);
			for(int j=head[i];j;j=e[j].next)
			{
				mul.erase(size[e[j].to]);
				mul.insert(size[e[j].to]-1);
			}
			std::multiset<int>::iterator it;
			it=mul.end();
			it--;
			maxn=std::max(maxn,sze+*it-1);
			for(int j=head[i];j;j=e[j].next)
			{
				mul.erase(size[e[j].to]-1);
				mul.insert(size[e[j].to]);
			}
			mul.insert(size[i]);
		}
		printf("%d\n",maxn);
	}
	return 0;
}

#include<stdio.h>
#include<set>
struct edge
{
	int to,next;
}e[400010];
int head[200010];
int sum;
void add(int from,int to)
{
	e[++sum].to=to;
	e[sum].next=head[from];
	head[from]=sum;
}
int size[200010];
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int n;
		sum=0;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			size[i]=0;
			head[i]=0;
		}
		for(int i=1;i<n;i++)
		{
			int u,v;
			scanf("%d%d",&u,&v);
			add(u,v);
			add(v,u);
			size[u]++;
			size[v]++;
		}
		std::multiset<int> mul;
		for(int i=1;i<=n;i++)
			mul.insert(size[i]);
		int maxn=0;
		for(int i=1;i<=n;i++)
		{
//			for(auto it:mul)
//				printf("%d ",it);
//			printf("\n");
			int sze=size[i];
			mul.erase(mul.find(size[i]));
			for(int j=head[i];j;j=e[j].next)
			{
				mul.erase(mul.find(size[e[j].to]));
				mul.insert(size[e[j].to]-1);
			}
			std::multiset<int>::iterator it;
			it=mul.end();
			it--;
			maxn=std::max(maxn,sze+*it-1);
			for(int j=head[i];j;j=e[j].next)
			{
				mul.erase(mul.find(size[e[j].to]-1));
				mul.insert(size[e[j].to]);
			}
			mul.insert(size[i]);
		}
		printf("%d\n",maxn);
	}
	return 0;
}

Answer: 2