#include<iostream>
#include<queue>
#include<set>
#include<vector>
using namespace std;

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

	vector< vector<int> > g(n + 1);
	for(int i = 0; i < n - 1; i++) {
		int a, b;
		cin >> a >> b;

		g[a].push_back(b);
		g[b].push_back(a);
	}

	if(n == 2) {
		cout << 0 << endl;
		return;
	}

	if(n == 3) {
		cout << 1 << endl;
		return;
	}

	priority_queue<int> pq;

	for(auto &itr: g) {
		pq.push(itr.size());
	}

	int maxi = pq.top();
	pq.pop();
	int second_maxi = pq.top();
	pq.pop();

	int count = 0;
	for(auto &node: g) {
		if(node.size() == second_maxi) {
			count++;
		}
	}

	bool found = false;
	for(auto &node: g) {
		if(node.size() != maxi) continue;

		int current_count = 0;
		for(auto &neigh: node) {
			if(g[neigh].size() == second_maxi) {
				current_count++;
			}
		}

		if(maxi == second_maxi) {
			if(current_count < count - 1) {
				found = true;
				break;
			}
		} else {
			if(current_count < count) {
				found = true;
				break;
			}
		}
	}

	if(found) {
		cout << maxi + second_maxi - 1<< endl;
	} else {
		cout << maxi + second_maxi - 2 << endl;
	}

	return;
}

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

	while(t-- > 0) {
		solve();
	}

	return 0;
}

#include<iostream>
#include<queue>
#include<set>
#include<vector>
using namespace std;

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

	vector< vector<int> > g(n + 1);
	for(int i = 0; i < n - 1; i++) {
		int a, b;
		cin >> a >> b;

		g[a].push_back(b);
		g[b].push_back(a);
	}

	priority_queue<int> pq;

	for(auto &itr: g) {
		pq.push(itr.size());
	}

	int maxi = pq.top();
	pq.pop();
	int second_maxi = pq.top();
	pq.pop();

	bool global_found = false;
	for(auto &node: g) {
		if(node.size() != maxi) continue;

		bool found = false;
		for(auto &neigh: node) {
			if(g[neigh].size() == second_maxi) {
				found = true;
				break;
			}
		}

		if(found) continue;
		global_found = true;
	}

	if(global_found) {
		cout << maxi + second_maxi - (maxi == 1) - (second_maxi == 1) << endl;
	} else {
		cout << maxi + second_maxi - 1 - (second_maxi == 1) << endl;
	}

	return;
}

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

	while(t-- > 0) {
		solve();
	}

	return 0;
}

Answer: 1


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

#define all(v) v.begin(), v.end()
#define debug(x) cout << #x << '=' << x << endl;
#define pb push_back
#define int long long
const long long M = 998244353;

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

    vector<vector<int>> vec(n+1);
    unordered_set<int> st;
    for(int i = 1; i <n; i++){
        int a, b; cin>>a>>b;
        vec[a].push_back(b);
        vec[b].push_back(a);
        st.insert((a*1e6+b));
        st.insert((b*1e6+a));
    }
    if(n<=4){
        cout<<n-2<<endl;
        return;
    }

    vector<pair<int, int>> sz;
    for(int i = 1; i <=n; i++){
        sz.push_back({vec[i].size(), i});
    }
    sort(sz.begin(), sz.end());

    for(int i = n-2; i >=0; i--){
        if(sz[i].first < sz[n-2].first){
            break;
        }
        if(st.count((sz[n-1].second*1e6 + sz[i].second)) == 0){
            cout<<sz[n-1].first+ sz[i].first-1<<endl;
            return;
        }
    }

    cout<<sz[n-1].first+ sz[n-2].first-2<<endl;

}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

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

    return 0;
}

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

#define all(v) v.begin(), v.end()
#define debug(x) cout << #x << '=' << x << endl;
#define pb push_back
#define int long long
const long long M = 998244353;

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

    vector<vector<int>> vec(n+1);
    unordered_set<int> st;
    for(int i = 1; i <n; i++){
        int a, b; cin>>a>>b;
        vec[a].push_back(b);
        vec[b].push_back(a);
        st.insert((a*1e6+b));
        st.insert((b*1e6+a));
    }
    if(n<=4){
        cout<<n-2<<endl;
        return;
    }

    vector<pair<int, int>> sz;
    for(int i = 1; i <=n; i++){
        // cout<<vec[i].size()<<" ";
        sz.push_back({vec[i].size(), i});
    } //cout<<endl;
    sort(sz.begin(), sz.end());

    int ans = sz[n-1].first+ sz[n-2].first-2;

    if(st.count((sz[n-1].second*1e6+sz[n-2].second)) == 0) ans++;

    for(int i = n-3; i >=0; i--){
        if(st.count((sz[n-1].second*1e6+sz[i].second)) == 0) ans = max(ans, sz[n-1].first+sz[i].first-1);
        else ans = max(ans, sz[n-1].first+sz[i].first-2);

        if(st.count((sz[n-2].second*1e6+sz[i].second)) == 0) ans = max(ans, sz[n-2].first+sz[i].first-1);
        else ans = max(ans, sz[n-2].first+sz[i].first-2);
    }

    cout<<ans<<endl;

}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t;
    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);
		}
		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;
}

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

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

	for(ll j=1;j<=t;j++) {
		ll z;
		cin >> z;
		vector<set<ll>> tree(z + 1);
		vector<ll> v;
		for (ll i = 0; i < z - 1; i++) {
			ll x, y;
			cin >> x >> y;
			v.push_back(x);
			v.push_back(y);
			tree[x].insert(y);
			tree[y].insert(x);
		}
		if(j==1142)
		{
			for(ll i=0;i<v.size();i++)
			{
				cout<<v[i];
			}
			cout<<endl;
		}
	  bool isall2=0;
	  ll count1=0,count2=0;
	  for(ll i=1;i<=z;i++)
	  {
	  	if(tree[i].size()==1)
		{
			count1++;
		}
		else if(tree[i].size()==2)
		{
			count2++;
		}
	  }

	  if(z>=5&&count2==z-2&&count1==2)
	  {
	  	isall2=1;
	  }
		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;
		if(isall2)
		{
			cout<<"3"<<endl;
		}
		else{
		cout << ans << endl;
		}
	}

	return 0;
}

Answer: 1


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define mp(x,y) make_pair(x,y)
#define inf (1e9)
#define INF (1e18)
#define eps (1e-8)
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ull unsigned long long
#define int long long
#define Int __int128
typedef long long LL;
mt19937 rnd(time(0));
const int N = 2e5 + 10, M = 1e6 + 10, mod = 1e9 + 7;
int n, in[N];
vector<int> g[N];

void solve()
{
    int ans = 0;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        g[i].clear();
        in[i] = 0;
    }
    for (int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        g[x].push_back(y);
        in[y]++;
        g[y].push_back(x);
        in[x]++;
    }
    multiset<int> s;
    for (int i = 1; i <= n; i++) {
        s.insert(in[i]);
    }
    for (int i = 1; i <= n; i++) {
        int res = 0;
        s.erase(s.find(in[i]));
        for (auto j : g[i]) {
            s.erase(s.find(in[j]));
            s.insert(in[j] - 1);
        }
        res = in[i] + *s.rbegin() - 1;
        ans = max(ans, res);
        for (auto j : g[i]) {
            s.erase(s.find(in[j] - 1));
            s.insert(in[j]);
        }
        s.insert(in[i]);
    }
    cout << ans << endl;
    return;
}

signed main()
{
	// IOS;
    // init();
	int __;
    cin >> __;
    while (__ --)
    solve();

	return 0;
}
//-Wl,--stack=1998244353

/*

*/

#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define mp(x,y) make_pair(x,y)
#define inf (1e9)
#define INF (1e18)
#define eps (1e-8)
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ull unsigned long long
#define int long long
#define Int __int128
typedef long long LL;
mt19937 rnd(time(0));
const int N = 2e5 + 10, M = 1e6 + 10, mod = 1e9 + 7;
int n, in[N], ver, mx = 0;
vector<int> g[N];

void dfs(int u, int fa) {
    if (g[u].size() > mx) {
        mx = g[u].size();
        ver = u;
    }
    for (int v : g[u]) {
        if (v == fa) continue;
        dfs(v, u);
    }
}

void solve()
{
    int ans = 1;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        g[i].clear();
        in[i] = 0;
    }
    for (int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        g[x].push_back(y);
        in[y]++;
        g[y].push_back(x);
        in[x]++;
    }
    mx = 0;
    for (int i = 1; i <= n; i++) {
        if (g[i].size() == 1) {
            dfs(i, -1);
            break;
        }
    }
    ans = g[ver].size();
    for (int v : g[ver]) {
        in[v]--;
    }
    mx = 0;
    for (int i = 1; i <= n; i++) {
        if (i == ver) continue;
        mx = max(mx, in[i]);
    }
    ans += mx - 1;
    cout << ans << endl;
    return;
}

signed main()
{
	// IOS;
    // init();
	int __;
    cin >> __;
    while (__ --)
    solve();

	return 0;
}
//-Wl,--stack=1998244353

/*

*/

Answer: 1


#if 1
#ifdef ONLINE_JUDGE
#define vangtruong ios_base::sync_with_stdio(false); cin.tie(nullptr)//Expert --> delete
#define debug(x) //*** debug ***//
#define debugVi(x) //*** debug ***//
#define debugVvi(x) //*** debug ***//
#else
#include "D:/05.Learning/01.Algorithm/01.Algorithms/debug.h"
#endif
#include<bits/stdc++.h>
using namespace std;
//*** define ***//
#define int long long
#define INF LONG_LONG_MAX
#define MP make_pair
#define FOR(_i,_a,_b) for(int _i = (_a); _i < (_b); _i++)
#define FORI(_i,_a,_b) for(int _i = (_a); _i <= (_b); _i++)
#define FORE(it,x) for(auto it = x.begin(); it != x.end(); ++it)
using vb = vector<bool>; using vvb = vector<vb>; using vi = vector<int>; using vvi = vector<vi>;
using vc = vector<char>; using vvc = vector<vc>; using pi = pair<int,int>; int itemp = 0; string stemp = "";
#endif
//**************************** CODING SPACE ****************************//
bool cmp(pi a,  pi b){
    return a.first > b.first;
}
int getAns(pi a, pi b, vvi& adj){
    // giam tat ca.
    // neu a b ke nhau return 1 + a - 1 + b - 2 = a.F + b.F -2// ko ke a+b
    bool isAdj = false;
    for(auto u: adj[a.second]) if(u == b.second) isAdj = true;
    return isAdj ? a.first + b.first -2ll : a.first + b.first -1ll;
}
void solve() {
    int n; cin >> n;
    vector<pi> L(n+1);
    vvi adj(n+1);
    vi D(n+1,0);
    FOR(i,0,n-1){
        int a, b; cin >> a >> b;
        D[a]++; D[b]++;
        adj[a].push_back(b); adj[b].push_back(a);
    }
    // make pi
    FOR(i,1,n+1) L[i] = MP(D[i],i);
    sort(L.begin(), L.end(), cmp);

    if(n == 2) {
        cout << "0\n"; return;
    }
    pi a = L[0], b = L[1], c = L[2];
    int ans = -INF;
    ans = max(ans, getAns(a, b, adj));
    ans = max(ans, getAns(a, c, adj));
    ans = max(ans, getAns(b, c, adj));
    cout << ans << "\n";
}

int32_t main() {
    vangtruong; int tcs = 1; cin >> tcs;
    while (tcs--) {solve();}return 0; }

#if 1
#ifdef ONLINE_JUDGE
#define vangtruong ios_base::sync_with_stdio(false); cin.tie(nullptr)//Expert --> delete
#define debug(x) //*** debug ***//
#define debugVi(x) //*** debug ***//
#define debugVvi(x) //*** debug ***//
#else
#include "D:/05.Learning/01.Algorithm/01.Algorithms/debug.h"
#endif
#include<bits/stdc++.h>
using namespace std;
//*** define ***//
#define int long long
#define INF LONG_LONG_MAX
#define MP make_pair
#define FOR(_i,_a,_b) for(int _i = (_a); _i < (_b); _i++)
#define FORI(_i,_a,_b) for(int _i = (_a); _i <= (_b); _i++)
#define FORE(it,x) for(auto it = x.begin(); it != x.end(); ++it)
using vb = vector<bool>; using vvb = vector<vb>; using vi = vector<int>; using vvi = vector<vi>;
using vc = vector<char>; using vvc = vector<vc>; using pi = pair<int,int>; int itemp = 0; string stemp = "";
#endif
//**************************** CODING SPACE ****************************//
bool cmp(pi a,  pi b){
    return a.first > b.first;
}
int getAns(pi a, vvi& adj, vi D){
    int res = D[a.second];
    D[a.second] = 0;
    for(auto u: adj[a.second]){
        D[u]--;
    }
    vector<pi> L(D.size());
    FOR(i,1,D.size()) L[i] = MP(D[i],i);
    sort(L.begin(), L.end(), cmp);
    // for(auto x : L) debug(x);
    res += L[0].first - 1ll;
    return res;
}
void solve() {
    int n; cin >> n;
    vector<pi> L(n+1);
    vvi adj(n+1);
    vi D(n+1,0);
    FOR(i,0,n-1){
        int a, b; cin >> a >> b;
        D[a]++; D[b]++;
        adj[a].push_back(b); adj[b].push_back(a);
    }
    // make pi
    FOR(i,1,n+1) L[i] = MP(D[i],i);
    sort(L.begin(), L.end(), cmp);
    if(n == 2) {
        cout << "0\n"; return;
    }
    pi a = L[0], b = L[1], c = L[2];
    int ans = -INF;
    ans = max(ans, getAns(a, adj, D));
    ans = max(ans, getAns(b, adj, D));
    ans = max(ans, getAns(c, adj, D));
    cout << ans << "\n";
}

int32_t main() {
    vangtruong; int tcs = 1; cin >> tcs;
    while (tcs--) {solve();}return 0; }

Answer: 2


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

#define ll long long int
#define pb push_back
#define mp make_pair
#define all(v) (v).begin(), (v).end()
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define vii vector<pii>
#define F first
#define S second
#define sz(x) ((int)(x).size())
#define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

const int MOD = 1e9 + 7;
const ll INF = 1e18;

template<typename T>
void debug(vector<T> v) { for(auto i: v) cout << i << " "; cout << endl; }

template<typename T1, typename T2>
void debug(vector<pair<T1, T2>> v) { for(auto i: v) cout << "(" << i.F << "," << i.S << ") "; cout << endl; }

int main() {
    fast_io;

    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<vector<int>>neighbours(n,vector<int>());
        vector<int>deg(n,0);
        for(int i=0;i<n-1;i++){
            int a,b;
            cin>>a>>b;
            neighbours[a-1].push_back(b-1);
            neighbours[b-1].push_back(a-1);
            deg[a-1]++;
            deg[b-1]++;
        }
        int maxi = 0;
        int conn = 1;
        vector<int>minis(n,INT_MAX);
        priority_queue< pair<int,int> ,vector<pair<int,int>> , greater<pair<int,int>> > pq;
        for(int i=0;i<n;i++){
            if(deg[i] == 1){
                minis[i] = 0;
               pq.push({0,i});
            }
        }

        while(!pq.empty()){
            pair<int,int> p  =pq.top();
            pq.pop();
            int node = p.second;
            int dist  =p.first;
            for(auto e : neighbours[node]){
                if(minis[e] > minis[node] + 1){
                    minis[e] = minis[node] + 1;
                    pq.push({minis[e] , e});
                }
            }

        }

        for(int i =1;i<n;i++){
            if(deg[maxi]  < deg[i] ){
                maxi = i;
            }
        }

        int optimal = maxi;
        for(int i = 0;i<n;i++){
            if(deg[i] == deg[maxi]){
                if(minis[i] < minis[maxi])optimal = i;
            }
        }
        // for(int i=0;i<n;i++){
        //     cout<<minis[i]<<" ";
        // }
        // cout<<endl;
        maxi = optimal;
        for(auto e:neighbours[maxi]){
            deg[e]--;
        }
        conn = conn -1 + deg[maxi];
        // cout<<"hello"<<maxi<<" " <<conn<<endl;
        deg[maxi] = INT_MIN;

        maxi = 0;
        for(int i =1;i<n;i++){
            if(deg[maxi]  < deg[i] ){
                maxi = i;
            }
        }
        conn = conn -1 + deg[maxi];
        // cout<<"hello"<<maxi<<" " <<conn<<endl;

        cout<<conn<<endl;

    }

    return 0;
}

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

#define ll long long int
#define pb push_back
#define mp make_pair
#define all(v) (v).begin(), (v).end()
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define vii vector<pii>
#define F first
#define S second
#define sz(x) ((int)(x).size())
#define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)

const int MOD = 1e9 + 7;
const ll INF = 1e18;

template<typename T>
void debug(vector<T> v) { for(auto i: v) cout << i << " "; cout << endl; }

template<typename T1, typename T2>
void debug(vector<pair<T1, T2>> v) { for(auto i: v) cout << "(" << i.F << "," << i.S << ") "; cout << endl; }

int main() {
    fast_io;

    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<vector<int>>neighbours(n,vector<int>());
        vector<int>deg(n,0);
        for(int i=0;i<n-1;i++){
            int a,b;
            cin>>a>>b;
            neighbours[a-1].push_back(b-1);
            neighbours[b-1].push_back(a-1);
            deg[a-1]++;
            deg[b-1]++;
        }
        if(n <= 2){
            cout<<0<<endl;
            continue;
        }
        int conn = 1;
        set<pair<int,int>>s;
        for(int i=0;i<n;i++){
            s.insert({deg[i],i});
        }
        for(int i=0;i<n;i++){
            int tconn = 1;
            pair<int,int>p = {deg[i] , i};
            s.erase(p);
            for(auto e : neighbours[i]){
                s.erase({deg[e],e});
                s.insert({deg[e]-1,e});
            }
            int deg_max = s.rbegin()->first;

            conn = max(conn , -1 + deg[i] + deg_max);
            s.insert(p);
            for(auto e : neighbours[i]){
                s.erase({deg[e]-1,e});
                s.insert({deg[e],e});
            }

        }

        cout<<conn<<endl;

    }

    return 0;
}

Answer: 2


#include <bits/stdc++.h>

using namespace std;

#ifndef ONLINE_JUDGE
#include "Ash.cpp"
#else
#define dbg(...)
#endif

void solve(int cs) {
  int n;
  cin >> n;
  vector<vector<int>> g(n);
  vector<int> deg(n, 0);
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v, --u, --v;
    ++deg[u], ++deg[v];
    g[u].push_back(v);
    g[v].push_back(u);
  }
  multiset<int> ms(deg.begin(), deg.end());
  int ans = 0;
  for (int i = 0; i < n; i++) {
    ms.erase(ms.find(deg[i]));
    for (auto &j : g[i]) {
      ms.erase(ms.find(deg[j]));
      ms.insert(deg[j] - 1);
    }
    ans = max(ans, deg[i] + *ms.rbegin() - 1);
    for (auto &j : g[i]) {
      ms.erase(ms.find(deg[j] - 1));
      ms.insert(deg[j]);
    }
    ms.insert(deg[i]);
  }
  cout << ans << "\n";
}

int32_t main() {
  ios::sync_with_stdio(!cin.tie(0));
  int t = 1;
  cin >> t;
  for (int i = 1; i <= t; ++i) {
    solve(i);
  }
  return 0;
}

#include <bits/stdc++.h>

using namespace std;

#ifndef ONLINE_JUDGE
#include "Ash.cpp"
#else
#define dbg(...)
#endif

void solve(int cs) {
  int n;
  cin >> n;
  vector<set<int>> g(n);
  vector<int> deg(n, 0);
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v, --u, --v;
    ++deg[u], ++deg[v];
    g[u].insert(v);
    g[v].insert(u);
  }
  if (n == 2) {
    cout << "0\n"; return;
  }
  int mx = *max_element(deg.begin(), deg.end());
  int who = -1;
  for (int i = 0; i < n; i++) {
    if (deg[i] == mx) {
      who = i;
    }
  }
  for (auto &them : g[who]) {
    g[them].erase(who);
  }
  g[who].clear(), deg.clear();
  for (int i = 0; i < n; i++) {
    deg[i] = g[i].size();
  }
  mx = *max_element(deg.begin(), deg.end());
  assert(deg[who] == 0);
  int second = -1;
  for (int i = 0; i < n; i++) {
    if (deg[i] == mx && i != who) {
      second = i;
    }
  }
  for (auto &them : g[second]) {
    g[them].erase(second);
  }
  g[second].clear();
  int ans = 0;
  vector<int> vis(n, false);
  auto dfs = [&](auto &&self, int node) -> void {
    vis[node] = true;
    for (auto &son : g[node]) {
      if (!vis[son]) {
        self(self, son);
      }
    }
  };
  for (int i = 0; i < n; i++) {
    if (!vis[i]) {
      ++ans, dfs(dfs, i);
    }
  }
  cout << ans - 2 << "\n";
}

int32_t main() {
  ios::sync_with_stdio(!cin.tie(0));
  int t = 1;
  cin >> t;
  for (int i = 1; i <= t; ++i) {
    solve(i);
  }
  return 0;
}

Answer: 1


/* package codechef; // don't place package name! */

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

public class Main {

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

class FastReader {

    BufferedReader br;
    StringTokenizer st;

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

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

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

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

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

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

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

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

class Task {

    PrintWriter out;
    FastReader sc;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public long exp(long a, long b, long mod) {
        long ans = 1L;
        while (b > 0) {
            if ((b & 1) > 0) {
                ans = (ans * a) % mod;
            }
            a = (a * a) % mod;
            b >>= 1;
        }
        return ans;
    }

    int t, n;
    int[] cal(int[] in, int n){
        int max = 0, v = 0;
        for(int i = 1;i<=n;i++){
            if(in[i]>=max){
                max = in[i];
                v = i;
            }
        }
        return new int[]{max-1, v};
    }
    public void solve() throws IOException {
        t = sc.nextInt();
        while (t-- > 0) {
            int n = i();
            int[] in = new int[n+1];
            List<int[]> edge = new ArrayList<>();
            for(int i = 1;i<n;i++){
                int x = i(), y = i();
                in[x]++;
                in[y]++;
                edge.add(new int[]{x, y});
            }
            int[] res = cal(in, n);
            int ans = res[0]+1;
            int v = res[1];
            in = new int[n+1];
            for(int[] e: edge){
                if(e[0]==v||e[1]==v) continue;
                in[e[0]]++;
                in[e[1]]++;
            }
            res = cal(in, n);
            ans+= res[0];
            out.print(ans);
            out.print("\n");
        }
    }
}

/* package codechef; // don't place package name! */

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

public class Main {

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

class FastReader {

    BufferedReader br;
    StringTokenizer st;

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

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

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

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

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

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

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

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

class Task {

    PrintWriter out;
    FastReader sc;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Answer: 2


#include <bits/stdc++.h>
#define ull unsigned long long
#define ul unsigned long
#define l long
#define ll long long
using namespace std;
struct vertex{
	vector<int> v;
	int degree;
};
vertex graph[200010];
int main()
{
	ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
	int t;
	cin>>t;
	while(t--)
	{
		multiset<int> dg;
		dg.clear();
		int n;
		cin>>n;
		int maxdegree=0;
		for(int i=1;i<=n;i++)
		{
			graph[i].v.clear();
			graph[i].degree=0;
		}
		for(int i=1;i<n;i++)
		{
			int u,v;
			cin>>u>>v;
			graph[u].v.push_back(v);
			graph[u].degree++;
			graph[v].v.push_back(u);
			graph[v].degree++;
			if(graph[u].degree>maxdegree)
				maxdegree=graph[u].degree;
			if(graph[v].degree>maxdegree)
				maxdegree=graph[v].degree;
		}
		for(int i=1;i<=n;i++)dg.insert(graph[i].degree);
		int ans=0;
		for(int i=1;i<=n;i++)
		{
			dg.erase(dg.find(graph[i].degree));
			for(auto it=graph[i].v.begin();it!=graph[i].v.end();it++)
			{
				int vv=*it;
				dg.erase(dg.find(graph[vv].degree));
				dg.insert(graph[vv].degree-1);
			}
			ans=max(ans,graph[i].degree+*dg.rbegin()-1);
			for(auto it=graph[i].v.begin();it!=graph[i].v.end();it++)
			{
				int vv=*it;
				dg.erase(dg.find(graph[vv].degree-1));
				dg.insert(graph[vv].degree);
			}
			dg.insert(graph[i].degree);
		}
 		cout<<ans<<endl;
	}
	return 0;
}

#include <bits/stdc++.h>
#define ull unsigned long long
#define ul unsigned long
#define l long
#define ll long long
using namespace std;
struct vertex{
	vector<int> v;
	int degree;
};
vertex graph[200010];
int main()
{
	ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		int maxdegree=0,maxsite;
		for(int i=1;i<=n;i++)
		{
			graph[i].v.clear();
			graph[i].degree=0;
		}
		for(int i=1;i<n;i++)
		{
			int u,v;
			cin>>u>>v;
			graph[u].v.push_back(v);
			graph[u].degree++;
			graph[v].v.push_back(u);
			graph[v].degree++;
			if(graph[u].degree>maxdegree)
			{
				maxdegree=graph[u].degree;
				maxsite=u;
			}
			if(graph[v].degree>maxdegree)
			{
				maxdegree=graph[v].degree;
				maxsite=v;
			}
		}
		int ans=1;
		ans+=maxdegree-1;
		graph[maxsite].degree=0;
		for(auto it=graph[maxsite].v.begin();it!=graph[maxsite].v.end();it++)
		{
			int vv=*it;
			graph[vv].degree--;
		}
		maxdegree=0;
		for(int i=1;i<=n;i++)
		{
			if(graph[i].degree>maxdegree)
				maxdegree=graph[i].degree;
		}
		ans+=maxdegree-1;
		cout<<ans<<endl;
	}
	return 0;
}

Answer: 1


#include <bits/stdc++.h>
using namespace std;
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("Ofast,unroll-loops,fast-math,O3")

#define pb push_back
#define ll long long
//#define sort(all(v)) sort(v.begin(),v.end())

int mod = 998244353;
const int N = 4e5 + 10;
const int inf = 1e9;
int fact[200001];
ll binpow(ll a, ll b){
 if(b == 0) return 1;
 else if(b % 2 == 1) return (a * binpow(a, b - 1)) % mod;
 ll p = binpow(a,b / 2);
 return (p * p) % mod;
}
vector <int> g[N];
int sum[N],was[N];
void dfs(int u){
    was[u] = 1;
    if(sum[u] == 0 && u != 1) sum[u]++;
    for(int to : g[u]){
        if(was[to] != 0) continue;
        sum[u]++;
        dfs(to);
    }
}
signed main(){
    //freopen("mootube.in", "r", stdin);
    //freopen("mootube.out", "w", stdout);
    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        for(int i = 1; i < n; i++){
            int u,v;
            cin >> u >> v;
            g[u].pb(v);
            g[v].pb(u);
        }
        dfs(1);
        int mx = 0;
        multiset<int> mt;
        for(int i = 1; i <= n; i++){
            mx = max(mx,sum[i]);
            mt.insert(sum[i]);
        }
        int mx1 = 0,v = 0,ans = 1;
        for(int i = 1; i <= n; i++){
            if(sum[i] == mx){
                for(int to : g[i]){
                    mt.erase(mt.find(sum[to]));
                    mt.insert(sum[to] - 1);
                }
                if(mx1 <= *mt.rbegin()){
                    mx1 = *mt.rbegin();
                    v = i;
                }
                for(int to : g[i]){
                    mt.erase(mt.find(sum[to] - 1));
                    mt.insert(sum[to]);
                }
            }
        }
        ans += mx - 1;
        for(int to : g[v]){
            sum[to]--;
        }
        mx = 0;
        for(int i = 1; i <= n; i++){
            if(v == i) continue;
            mx = max(mx,sum[i]);
        }
        cout << ans + mx - 1 << '\n';
        for(int i = 1; i <= n; i++){
            sum[i] = was[i] = 0;
            g[i].clear();
        }
    }
}

#include <bits/stdc++.h>
using namespace std;
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("Ofast,unroll-loops,fast-math,O3")

#define pb push_back
#define ll long long
//#define sort(all(v)) sort(v.begin(),v.end())

int mod = 998244353;
const int N = 4e5 + 10;
const int inf = 1e9;
int fact[200001];
ll binpow(ll a, ll b){
 if(b == 0) return 1;
 else if(b % 2 == 1) return (a * binpow(a, b - 1)) % mod;
 ll p = binpow(a,b / 2);
 return (p * p) % mod;
}
vector <int> g[N];
int sum[N],was[N];
void dfs(int u){
    was[u] = 1;
    if(sum[u] == 0 && u != 1) sum[u]++;
    for(int to : g[u]){
        if(was[to] != 0) continue;
        sum[u]++;
        dfs(to);
    }
}
signed main(){
    //freopen("mootube.in", "r", stdin);
    //freopen("mootube.out", "w", stdout);
    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        for(int i = 1; i < n; i++){
            int u,v;
            cin >> u >> v;
            g[u].pb(v);
            g[v].pb(u);
        }
        dfs(1);
        multiset<int> mt;
        for(int i = 1; i <= n; i++)mt.insert(sum[i]);
        int ans = 0;
        for(int i = 1; i <= n; i++){
            mt.erase(mt.find(sum[i]));
            for(int to : g[i]){
                mt.erase(mt.find(sum[to]));
                mt.insert(sum[to] - 1);
            }
            ans = max(ans,*mt.rbegin() + sum[i] - 1);
            for(int to : g[i]){
                mt.erase(mt.find(sum[to] - 1));
                mt.insert(sum[to]);
            }
            mt.insert(sum[i]);
        }
        cout << ans << '\n';
        for(int i = 1; i <= n; i++){
            sum[i] = was[i] = 0;
            g[i].clear();
        }
    }
}

Answer: 2


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

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

    vector<unordered_set<int>> adj(n + 1);
    vector<pair<int, int>> indeg;
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].insert(v);
        adj[v].insert(u);
    }
    for (int i = 1; i <= n; i++) {
        indeg.push_back({(int)adj[i].size(), i});
    }
    sort(indeg.rbegin(), indeg.rend());
    int ans = 0;
    for (int i = 0; i <n; i++) {
        int node1 = indeg[i].second;
        for (int j = i + 1; j < n; j++) {
            int node2 = indeg[j].second;
            if (node1 == node2) continue;
            if (adj[node1].count(node2)) {
                ans = max(ans, indeg[i].first + indeg[j].first - 2);
            } else {
                ans = max(ans, indeg[i].first + indeg[j].first - 1);
                break;
            }
        }
    }

    cout << ans << endl;
}

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

    int T;
    cin >> T;
    while (T--) solve();
}

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

void solve() {
    int n;
    cin >> n;
    vector<unordered_set<int>> adj(n + 1);
    map<int, int, less<int>> indeg;
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].insert(v);adj[v].insert(u);
        indeg[u]++; indeg[v]++;
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        for (auto &[node, degree] : indeg) {
            if(node==i) continue;
            else if (adj[i].count(node) ) {
                ans = max(ans, indeg[node] + indeg[i] - 2);
            } else {
                ans = max(ans, indeg[node] + indeg[i] - 1);
            }
        }
    }
    cout << ans << endl;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin >> T;
    while (T--) solve();
}

Answer: 1


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef vector<long long> vll;
#define reg(i,a,b) for(ll i=a;i<b;i++)
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;

void solve() {
    ll n;
    cin>>n;
    vector<vi> adjL(n);
    map<ll, ll> f;

    reg(i,0,n - 1){
        ll u, v;
        cin>>u>>v;
        u--;
        v--;
        adjL[u].push_back(v);
        adjL[v].push_back(u);
        f[u]++;
        f[v]++;
    }
    set<pair<ll,ll>> cont;
    for(auto it : f) cont.insert({it.second, it.first});
    ll node = (*cont.rbegin()).second;
    ll fre = f[node];
    ll ans = fre;
    cont.erase({fre, node});
    for(auto nxt: adjL[node]){
        cont.erase({f[nxt], nxt});
        f[nxt]--;
        cont.insert({f[nxt], nxt});
    }

    node =  (*cont.rbegin()).second;
    fre = f[node];
    ans += fre;
    ans--;
    cout<<ans<<endl;
    return;
}

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

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef vector<long long> vll;
#define reg(i,a,b) for(ll i=a;i<b;i++)
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;

ll s(set<pair<ll,ll>> &cont, ll node, map<ll, ll> &f, vector<vi> &adjL){
    ll ans = 0;
    ll fre = f[node];
    ans = fre;
    cont.erase({fre, node});
    for(auto nxt: adjL[node]){
        cont.erase({f[nxt], nxt});
        f[nxt]--;
        cont.insert({f[nxt], nxt});
    }

    ans += (*cont.rbegin()).first;
    ans--;
    for(auto nxt: adjL[node]){
        cont.erase({f[nxt], nxt});
        f[nxt]++;
        cont.insert({f[nxt], nxt});
    }
    return ans;
}

void solve() {
    ll n;
    cin>>n;
    vector<vi> adjL(n);
    map<ll, ll> f;

    reg(i,0,n - 1){
        ll u, v;
        cin>>u>>v;
        u--;
        v--;
        adjL[u].push_back(v);
        adjL[v].push_back(u);
        f[u]++;
        f[v]++;
    }
    set<pair<ll,ll>> cont;
    for(auto it : f) cont.insert({it.second, it.first});
    //ll node = (*cont.rbegin()).second;
    ll fre = (*cont.rbegin()).first;
    // cout<<fre<<endl;
    ll ans = -1;
    vector<pair<ll, ll>> temp(cont.begin(), cont.end());
    for(ll i = temp.size() - 1; i>=0; i--){
        if(temp[i].first < fre) break;
        // cout<<"chala"<<endl;
        // cout<<s(cont, temp[i].second, f, adjL)<<endl;
        ans = max(ans,s(cont, temp[i].second, f, adjL));
    }

    cout<<ans<<endl;
    return;
}

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

Answer: 2


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

#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) a / gcd(a, b) * b
#define N cout << "No\n"
#define Y cout << "Yes\n"
#define endl '\n'
#define all(a) a.begin(),a.end()
#define int long long
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define ll long long

void solve() {
    int n;
    cin >> n;
    vector <vector <int>> a(n+1);
    for (int i=1; i<n; i++) {
        int u, v;
        cin >> u >> v;
        a[u].push_back(v);
        a[v].push_back(u);
    }
    if (n == 2) {
        cout << 0 << endl;
    } else if (n == 3){
        cout << 1 << endl;
    } else if (n == 4) {
        cout << 2 << endl;
    } else {
        int res = 1;
        vector <pair <int, int>> num(n+1);
        for (int i=1; i<=n; i++) {
            num[i].first = a[i].size();
            num[i].second = i;
        }
        sort(all(num));
        res += num[n].first - 1;
        vector <pair <int, int>> kk(n+1);
        for (int i=1; i<=n; i++) {
            if (i == num[n].second) {
                continue;
            }
            kk[i].first = a[i].size();
            kk[i].second = i;
        }
        for (auto x : a[num[n].second]) {
            kk[x].first--;
        }
        sort(all(kk));
        res += kk[n].first - 1;
        cout << res << endl;
    }
}

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

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

#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) a / gcd(a, b) * b
#define N cout << "No\n"
#define Y cout << "Yes\n"
#define endl '\n'
#define all(a) a.begin(),a.end()
#define int long long
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define ll long long

void solve() {
    int n;
    cin >> n;
    vector <vector <int>> a(n+1);
    for (int i=1; i<n; i++) {
        int u, v;
        cin >> u >> v;
        a[u].push_back(v);
        a[v].push_back(u);
    }
    if (n == 2) {
        cout << 0 << endl;
    } else if (n == 3){
        cout << 1 << endl;
    } else if (n == 4) {
        cout << 2 << endl;
    } else {
        int ans = 1;
        vector <pair <int, int>> num(n+1);
        for (int i=1; i<=n; i++) {
            num[i].first = a[i].size();
            num[i].second = i;
        }
        sort(all(num));
        int p = n;
        int cnt = 0;
        while (num[p].first == num[n].first && cnt < 10) {
            int res = 1;
            res += num[p].first - 1;
            vector <pair <int, int>> kk(n+1);
            for (int i=1; i<=n; i++) {
                if (i == num[p].second) {
                    continue;
                }
                kk[i].first = a[i].size();
                kk[i].second = i;
            }
            for (auto x : a[num[p].second]) {
                kk[x].first--;
            }
            sort(all(kk));
            res += kk[n].first - 1;
            ans = max(ans, res);
            p--;
            cnt++;
        }
        cout << ans << endl;
    }
}

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

Answer: 2


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

// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// template <typename T>
// using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
typedef long long int ll;
ll M = 1e9+7;
const ll N = 2e5 + 5;
#define pb push_back
#define in insert
#define vll vector<ll>
#define pll pair<ll,ll>
#define vbl vector<bool>
#define vpll vector<pair<ll,ll>>
#define vvll vector<vector<ll>>
#define sll set<ll>
#define all(c) c.begin(),c.end()
#define msll multiset<ll>
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep1(i,n) for(ll i=1;i<=n;i++)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define geta(c,n) ll c[n]; for(ll i=0;i<n;i++)cin>>c[i];
#define endl "\n"

int main(){
    ll tt = 1 ;
    cin >> tt ;
    while(tt--){
        ll n ; cin >> n ;
        map<pll,ll> m ;
        vpll v;
        ll ct[n+1]={0};
        rep(i,n-1){
            ll x,y ; cin >> x>> y;
            ct[x]++;
            ct[y]++;
            m[{x,y}]++;
            m[{y,x}]++;
        }
        rep1(i,n)v.pb({ct[i],i});
        sort(all(v));
        reverse(all(v));
        ll ans = v[0].first;
        rep1(i,v.size()-1){
            if(m[{v[0].second,v[i].second}])ans=max(ans,v[0].first+v[i].first-1);
            else ans=max(ans,v[0].first+v[i].first);
        }
        cout<<ans-1<<endl;
    }
}

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

// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// template <typename T>
// using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
typedef long long int ll;
ll M = 1e9+7;
const ll N = 2e5 + 5;
#define pb push_back
#define in insert
#define vll vector<ll>
#define pll pair<ll,ll>
#define vbl vector<bool>
#define vpll vector<pair<ll,ll>>
#define vvll vector<vector<ll>>
#define sll set<ll>
#define all(c) c.begin(),c.end()
#define msll multiset<ll>
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep1(i,n) for(ll i=1;i<=n;i++)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define geta(c,n) ll c[n]; for(ll i=0;i<n;i++)cin>>c[i];
#define endl "\n"

int main(){
    ll tt = 1 ;
    cin >> tt ;
    while(tt--){
        ll n ; cin >> n ;
        map<pll,ll> m ;
        vpll v;
        ll ct[n+1]={0};
        rep(i,n-1){
            ll x,y ; cin >> x>> y;
            ct[x]++;
            ct[y]++;
            m[{x,y}]++;
            m[{y,x}]++;
        }
        rep1(i,n)v.pb({ct[i],i});
        sort(all(v));
        reverse(all(v));
        ll ans = v[0].first;
        rep1(i,v.size()-1){
            if(m[{v[0].second,v[i].second}])ans=max(ans,v[0].first+v[i].first-1);
            else ans=max(ans,v[0].first+v[i].first);
            if(i>1){
                if(m[{v[1].second,v[i].second}])ans=max(ans,v[1].first+v[i].first-1);
                else ans=max(ans,v[1].first+v[i].first);
            }
        }
        cout<<ans-1<<endl;
    }
}

Answer: 2


#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <map>
#include <set>

using namespace std;
typedef long long ll;

void solve()
{
    int n;
    cin>>n;
    vector<vector<int>> g(n+1);
    vector<int> ind(n+1,0);

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

    int tag=0,cnt=0;
    for(int i=1;i<=n;++i)
        if(ind[i]>ind[tag]) tag=i,cnt=1;
        else if(ind[i]==ind[tag]) cnt++;

    if(cnt>=3) cout<<ind[tag]*2-1<<'\n';
    else if(cnt==2)
    {
        bool is = false;
        for(int i=0;i<(int)g[tag].size();++i)
            if(ind[g[tag][i]]==ind[tag]) is = true;
        if(is) cout<< ind[tag]*2-2<< '\n';
        else cout<< ind[tag]*2-1<< '\n';
    }
    else
    {
        for(int i=0;i<(int)g[tag].size();++i) ind[g[tag][i]]--;
        int mx=0;
        for(int i=1;i<=n;++i)
            if(i!=tag) mx = max(mx,ind[i]);
        cout<< ind[tag]+mx-1<< '\n';
    }

}

int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    //fflush(stdout);

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

    return 0;
}

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <map>
#include <set>

using namespace std;
typedef long long ll;

void solve()
{
    int n;
    cin>>n;
    vector<vector<int>> g(n+1);
    vector<int> ind(n+1,0);

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

    int tag=0,cnt=0;
    for(int i=1;i<=n;++i)
        if(ind[i]>ind[tag]) tag=i,cnt=1;
        else if(ind[i]==ind[tag]) cnt++;

    if(cnt>=3) cout<<ind[tag]*2-1<<'\n';
    else if(cnt==2)
    {
        bool is = false;
        for(int i=0;i<(int)g[tag][i];++i)
            if(ind[g[tag][i]]==ind[tag]) is = true;
        if(is) cout<< ind[tag]*2-2<< '\n';
        else cout<< ind[tag]*2-1<< '\n';
    }
    else
    {
        for(int i=0;i<(int)g[tag].size();++i) ind[g[tag][i]]--;
        int mx=0;
        for(int i=1;i<=n;++i)
            if(i!=tag) mx = max(mx,ind[i]);
        cout<< ind[tag]+mx-1<< '\n';
    }

}

int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    //fflush(stdout);

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

    return 0;
}

Answer: 1


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
bool cmp(pair<ll,ll>a,pair<ll,ll>b){
return a.second>b.second;
}
void solve(ll tc)
{
    ll n,i,x,y,s=0,qq,ww,s2=0,ee,m;
    cin>>n;
    vector<pair<ll,ll>>p(n+9);
    for(i=1;i<=n;i++) p[i].first=i,p[i].second=0;
    vector<set<ll>> ps(n+3);
    for(i=1;i<n;i++){
        cin>>x>>y;
        p[x].second++;
        p[y].second++;
        ps[x].insert(y);
        ps[y].insert(x);
    }
    sort(p.begin(),p.end(),cmp);

    s=p[0].second;
    qq=p[0].first;
    m=min(n,s+2);
    for(i=1;i<m;i++){
        ww=p[i].second;
        ee=p[i].first;
        if(ps[ee].count(qq)) ww--;
        s2=max(s2,ww);

    }
    ll ans=s+s2-1;
    s=p[1].second;
    qq=p[1].first;
    m=min(n,s+2);
    for(i=2;i<m;i++){
        ww=p[i].second;
        ee=p[i].first;
        if(ps[ee].count(qq)) ww--;
        s2=max(s2,ww);

    }
    ans=max(ans,s+s2-1);
    cout<<ans<<endl;

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int tc=1;
    cin>>tc;
    for(ll i=1; i<=tc; i++)
    {
        solve(i);
    }
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
bool cmp(pair<ll,ll>a,pair<ll,ll>b){
return a.second>b.second;
}
void solve(ll tc)
{
    ll n,i,x,y,s=0,qq,ww,s2=0,ee;
    cin>>n;
    vector<pair<ll,ll>>p(n+3);
    for(i=1;i<=n;i++) p[i].first=i,p[i].second=0;
    vector<set<ll>> ps(n+3);
    for(i=1;i<n;i++){
        cin>>x>>y;
        p[x].second++;
        p[y].second++;
        ps[x].insert(y);
        ps[y].insert(x);
    }
    sort(p.begin(),p.end(),cmp);

    s=p[0].second;
    qq=p[0].first;
    for(i=1;i<n;i++){
        ww=p[i].second;
        ee=p[i].first;
        if(ps[ee].count(qq)) ww--;
        s2=max(s2,ww);

    }
    cout<<s+s2-1<<endl;

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int tc=1;
    cin>>tc;
    for(ll i=1; i<=tc; i++)
    {
        solve(i);
    }
}

Answer: 1


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

#define IOS ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define in_ freopen("input.txt", "r", stdin);
#define all(a) a.begin(), a.end()
#define cout2(a) for(int i = 0; i < a.size(); ++ i) cout << a[i] << " "; cout << "\n";
#define cout1(a, s, e) for(int i = s; i < e; ++ i) cout << a[i] << " "; cout << "\n";
#define debug1(x) cout << x << "!!!\n";
#define debug2(x) cout << x << "###\n";

typedef long long ll;
const int N = 200005;
typedef pair<int,int> PII;

#define x1 first
#define y1 second

void deal() {

	int n;
	cin >> n;

	vector<int> deg(n), a;
	vector<PII> e(n);

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

		u --, v --;
	    deg[u] ++, deg[v] ++;

	    e.push_back({u, v});
	}

	int ans = 0;
//	for(auto it : e) {
//		ans = max(ans, it.x1 + it.y1 - 2);
//	}
//
	int vmax = *max_element(deg.begin(), deg.end());

	for(int i = 0; i < n; ++ i) if(deg[i] == vmax) a.push_back(i);

	if(a.size() >= 3) {
		cout << 2 * vmax - 1 << "\n";
		return;
	}

	for(int j = 0; j < a.size(); ++j)  {
	    vmax = a[j];

		vector<int> ok(n);
		ok[vmax] = 1;

		for(auto it : e) {
			if(it.x1 == vmax) ok[it.y1] = 1;
			if(it.y1 == vmax) ok[it.x1] = 1;
		}

		for(int i = 0; i < n; ++ i) {
			if(i == vmax) continue;
			if(ok[i]) ans = max(ans, deg[vmax] + deg[i] - 2);
			else ans = max(ans, deg[vmax] + deg[i] - 1);
		}
    }

    cout << ans << "\n";

}

int main() {

	#ifndef ONLINE_JUDGE
	in_;
//	freopen("out.txt", "w", stdout);
	#endif

	IOS;

	int t;
	cin >> t;
	while(t--)
	 deal();

	return 0;
}

/*
       /\_/\
      (= ._.)
       />  \>  !!!!!!
       author :: fly

*/

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

#define IOS ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define in_ freopen("input.txt", "r", stdin);
#define all(a) a.begin(), a.end()
#define cout2(a) for(int i = 0; i < a.size(); ++ i) cout << a[i] << " "; cout << "\n";
#define cout1(a, s, e) for(int i = s; i < e; ++ i) cout << a[i] << " "; cout << "\n";
#define debug1(x) cout << x << "!!!\n";
#define debug2(x) cout << x << "###\n";

typedef long long ll;
const int N = 200005;
typedef pair<int,int> PII;

#define x1 first
#define y1 second

void deal() {

	int n;
	cin >> n;

	vector<int> deg(n), a;
	vector<PII> e(n);

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

		u --, v --;
	    deg[u] ++, deg[v] ++;

	    e.push_back({u, v});
	}

	int ans = 0;
//	for(auto it : e) {
//		ans = max(ans, it.x1 + it.y1 - 2);
//	}
//
	int vmax = *max_element(deg.begin(), deg.end());

	for(int i = 0; i < n; ++ i) if(deg[i] == vmax) a.push_back(i);

	for(int j = 0; j < a.size(); ++j)  {
	    vmax = a[j];

		vector<int> ok(n);
		ok[vmax] = 1;

		for(auto it : e) {
			if(it.x1 == vmax) ok[it.y1] = 1;
			if(it.y1 == vmax) ok[it.x1] = 1;
		}

		for(int i = 0; i < n; ++ i) {
			if(i == vmax) continue;
			if(ok[i]) ans = max(ans, deg[vmax] + deg[i] - 2);
			else ans = max(ans, deg[vmax] + deg[i] - 1);
		}
    }

    cout << ans << "\n";

}

int main() {

	#ifndef ONLINE_JUDGE
	in_;
//	freopen("out.txt", "w", stdout);
	#endif

	IOS;

	int t;
	cin >> t;
	while(t--)
	 deal();

	return 0;
}

/*
       /\_/\
      (= ._.)
       />  \>  !!!!!!
       author :: fly

*/

Answer: 1


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

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

    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        if(n == 1){
            cout << 0 << "\n";
            continue;
        }

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

        for (int i = 1; i <= n; i++){
            sort(adj[i].begin(), adj[i].end());
        }

        vector<pair<int,int>> vertices;
        vertices.reserve(n);
        for(int i = 1; i <= n; i++){
            vertices.push_back({degree[i], i});
        }
        sort(vertices.begin(), vertices.end(), [&](auto &a, auto &b){
            return a.first > b.first;
        });

        // We only need to check the top k candidates.
        int k = n;
        int ans = 0;

        auto isAdjacent = [&](int u, int v) -> bool {

            return binary_search(adj[u].begin(), adj[u].end(), v);
        };

        for (int i = 0; i < k; i++){
            for (int j = i + 1; j < k; j++){
                int u = vertices[i].second;
                int v = vertices[j].second;
                if (!isAdjacent(u, v)){
                    ans = max(ans, vertices[i].first + vertices[j].first);

                    break;
                }
            }
        }
        int maxi=0;
        for(int  i=0;i<n-1;i++) maxi=max(maxi,degree[v1[i].first]+degree[v1[i].second]-1);
        cout << max(maxi-1,ans-1) << "\n";
    }
    return 0;
}

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

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

    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        if(n == 1){
            cout << 0 << "\n";
            continue;
        }

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

        for (int i = 1; i <= n; i++){
            sort(adj[i].begin(), adj[i].end());
        }

        vector<pair<int,int>> vertices;
        vertices.reserve(n);
        for(int i = 1; i <= n; i++){
            vertices.push_back({degree[i], i});
        }
        sort(vertices.begin(), vertices.end(), [&](auto &a, auto &b){
            return a.first > b.first;
        });

        int k = min(n, (int)5000);
        int ans = 0;

        auto isAdjacent = [&](int u, int v) -> bool {

            return binary_search(adj[u].begin(), adj[u].end(), v);
        };

        for (int i = 0; i < k; i++){
            for (int j = i + 1; j < k; j++){
                int u = vertices[i].second;
                int v = vertices[j].second;
                if (!isAdjacent(u, v)){
                    ans = max(ans, vertices[i].first + vertices[j].first);

                    break;
                }
            }
        }
        int maxi=0;
        for(int  i=0;i<n-1;i++) maxi=max(maxi,degree[v1[i].first]+degree[v1[i].second]-1);
        cout << max(maxi-1,ans-1) << "\n";
    }
    return 0;
}
j < k; j++){
                int u = vertices[i].second;
                int v = vertices[j].second;
                if (!isAdjacent(u, v)){
                    ans = max(ans, vertices[i].first + vertices[j].first);
                    // For fixed i, the first valid j gives the best sum with vertex u.
                    break;
                }
            }
        }
        int maxi=0;
        for(int  i=0;i<n-1;i++) maxi=max(maxi,degree[v1[i].first]+degree[v1[i].second]-1);
        cout << max(maxi-1,ans-1) << "\n";
    }
    return 0;
}

Answer: 1


#pragma GCC optimize("O3,unroll-loops")

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace chrono;
using namespace __gnu_pbds;

template<class T> using oset =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update >; // *find_by_order, order_of_key -- gives the number of elements smaller than the number searched

#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define forn(i,a,n) for (long long i=a; i<n; ++i)

#define int long long
#define double long double

#define pb push_back
#define ppb pop_back
// #define mp make_pair
#define ff first
#define ss second
#define sz(x) ((int)(x).size())
#define nline "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define seea(a,n) for (long long i=0; i<n; ++i) {cin>>a[i]}
#define seev(v,n) for (long long i=0; i<n; ++i) {long long x; cin>>x; v.push_back(x);}
#define sees(s,n) for (long long i=0; i<n; ++i) {long long x; cin>>x; s.insert(x);}

#define yeah cout<<"YES\n"
#define nah cout<<"NO\n"
#define nl cout<<"\n"
#define endl "\n"

#define MOD 1000000007
#define MOD1 998244353
#define INF 1e18
#define PI 3.141592653589793238462

#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;

void _print(int t) {cerr<<t;}
void _print(string t) {cerr<<t;}
void _print(char t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(unsigned long long t) {cerr<<t;}

template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}

bool isPrime(int n){ for (int i = 2; i * i <= n; i++){ if (n % i == 0){ return false; }} return true; }
int nextPrime(int n){ n++; while(!isPrime(n)){ n++; } return n; }
int gcd(int a, int b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
int expo(int a, int b, int mod) {int res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
int mminvprime(int a, int b) {return expo(a, b - 2, b);}
int mod_add(int a, int b, int m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
int mod_mul(int a, int b, int m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
int mod_sub(int a, int b, int m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
int mod_div(int a, int b, int m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;}  //only for prime m

// int a[300001], b[300001];
void solve(){

int n,ans = 0;
 cin>>n;
map<int,int>degree;
vector<pair<int,int>>vec;
set<pair<int,int>>edge;
map<int,list<int>>mp;
int m1 = 0,m2 = 0,maxx = 0;

for (int i = 1; i < n; i++)
{
    int u,v;cin>>u>>v;degree[u]++;degree[v]++;
    mp[u].pb(v); mp[v].pb(u);
    edge.insert({u,v});
    edge.insert({v,u});
}

for (int i = 1; i <= n; i++)
{
    for (auto  j : mp[i])
    {
           ans = max(ans, degree[i] + degree[j] - 2);
    }
    vec.pb({degree[i],i});
    }

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

for (int i = n-1; i >= 0; i--)
{   int j = i-1;
    for (; j >= 0 && edge.find({vec[i].second,vec[j].second}) != edge.end(); j--)
    {
        1;
    }
    if(j >= 0){
        ans = max(ans, vec[i].first+vec[j].first - 1);
    }
}

cout<<ans<<endl;

   }

int32_t main()
{
fastio();
int t = 1;
cin>>t;

for (int i = 0; i < t; i++)
{
    solve();

}

 return 0;
}

#pragma GCC optimize("O3,unroll-loops")

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace chrono;
using namespace __gnu_pbds;

template<class T> using oset =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update >; // *find_by_order, order_of_key -- gives the number of elements smaller than the number searched

#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)

#define forn(i,a,n) for (long long i=a; i<n; ++i)

#define int long long
#define double long double

#define pb push_back
#define ppb pop_back
// #define mp make_pair
#define ff first
#define ss second
#define sz(x) ((int)(x).size())
#define nline "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define seea(a,n) for (long long i=0; i<n; ++i) {cin>>a[i]}
#define seev(v,n) for (long long i=0; i<n; ++i) {long long x; cin>>x; v.push_back(x);}
#define sees(s,n) for (long long i=0; i<n; ++i) {long long x; cin>>x; s.insert(x);}

#define yeah cout<<"YES\n"
#define nah cout<<"NO\n"
#define nl cout<<"\n"
#define endl "\n"

#define MOD 1000000007
#define MOD1 998244353
#define INF 1e18
#define PI 3.141592653589793238462

#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;

void _print(int t) {cerr<<t;}
void _print(string t) {cerr<<t;}
void _print(char t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(unsigned long long t) {cerr<<t;}

template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}

bool isPrime(int n){ for (int i = 2; i * i <= n; i++){ if (n % i == 0){ return false; }} return true; }
int nextPrime(int n){ n++; while(!isPrime(n)){ n++; } return n; }
int gcd(int a, int b) {if (b > a) {return gcd(b, a);} if (b == 0) {return a;} return gcd(b, a % b);}
int expo(int a, int b, int mod) {int res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
int mminvprime(int a, int b) {return expo(a, b - 2, b);}
int mod_add(int a, int b, int m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
int mod_mul(int a, int b, int m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
int mod_sub(int a, int b, int m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
int mod_div(int a, int b, int m) {a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m;}  //only for prime m

// int a[300001], b[300001];
void solve(){

int n; cin>>n;
map<int,int>degree;
map<int,list<int>>mp;
int m1 = 0,m2 = 0,maxx;
for (int i = 1; i < n; i++)
{
    int u,v;cin>>u>>v;degree[u]++;degree[v]++;
    mp[u].pb(v); mp[v].pb(u);
}
for (int i = 1; i <= n; i++)
{
    if(degree[i] >= m1){maxx = i; m1 = degree[i];}
    // else{m2 = max(degree[i],m2);}
}

for (auto i : mp[maxx]){degree[i]--;}

for (int i = 1; i <= n && i != maxx; i++)
{
  if(degree[i] >= m2){ m2 = degree[i];}
}

// cout<<m1<<m2<<endl;
cout<<(-1+m1+m2)<<endl;

   }

int32_t main()
{
fastio();
int t = 1;
cin>>t;

for (int i = 0; i < t; i++)
{
    solve();

}

 return 0;
}

Answer: 1


import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
    {
	static FastScanner fs = null;
	static ArrayList<Set<Integer>> list;
	static int co[];
	public static void main(String[] args) {
		fs = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int t = fs.nextInt();
        while(t-->0){
            list = new ArrayList<>();
            int n = fs.nextInt();
            co = new int[n+1];
            for(int i = 0;i<=n;i++){
                Set<Integer> se = new HashSet<>();
                list.add(se);
            }
            for(int i = 1;i<n;i++){
                int u = fs.nextInt();
                int v = fs.nextInt();
                list.get(u).add(v);
                list.get(v).add(u);
                co[u]+=1;
                co[v]+=1;
            }
            //System.out.println("---------");
            int res = dfs(1,-1,0,0);
           // res = Math.min(res,n-2);
            out.println(res);
        }
		out.close();
	}
	static int dfs(int node,int par,int mx,int dif){
	    int sz = co[node];
	    int d1 = mx;
	    int d2 = dif;
	    if(sz>(mx-dif)){
	        dif = -1;
	        mx = sz;
	    }
	    else{
	        mx = mx;
	        dif = 0;
	    }
	    int ans = 0;
	    if(par!=-1){
	        ans = d1+d2+sz-1;
	    }
	    for(Integer p:list.get(node)){
	        if(p==par)
	        continue;
	        int re = dfs(p,node,mx,dif);
	        ans = Math.max(ans,re);
	    }

	    //System.out.println(d1+" -- "+d2+" --- "+node+" -- "+par+" -- "+sz);
	    return ans;
	}
	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
		double nextDouble() {
			return Double.parseDouble(next());
		}
	}
}

import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
    {
	static FastScanner fs = null;
	static int res;
	static ArrayList<Set<Integer>> list;
	static int co[];
	static Map<Integer,Integer> map;
	static TreeSet<Integer> ts;
	static int inf = (int)1e8;
	static boolean vis[];
	public static void main(String[] args) {
		fs = new FastScanner();

		PrintWriter out = new PrintWriter(System.out);
		int t = fs.nextInt();
        while(t-->0){
            list = new ArrayList<>();
            int n = fs.nextInt();
            co = new int[n+1];
            ts = new TreeSet<>();
            map = new HashMap<>();
            vis = new boolean[n+1];
            Arrays.fill(vis,false);
            for(int i = 0;i<=n;i++){
                Set<Integer> se = new HashSet<>();
                list.add(se);
            }
            for(int i = 1;i<n;i++){
                int u = fs.nextInt();
                int v = fs.nextInt();
                list.get(u).add(v);
                list.get(v).add(u);
                co[u]+=1;
                co[v]+=1;
            }
            for(int i = 1;i<=n;i++){
                int num = co[i];
                ts.add(num);
                if(map.get(num)==null){
                    map.put(num,1);
                }
                else{
                    map.replace(num,1+map.get(num));
                }
            }
            res = 0;
            //System.out.println("---------");
            dfs(1,-1);
            //out.println(res+" ------ ");
            dfs2(1);
           // res = Math.min(res,n-2);
            out.println(res);
        }
		out.close();
	}
	static void dfs2(int node){
	    vis[node] = true;
	    int ans1 = co[node];
	        map.replace(ans1,-1+map.get(ans1));
	        if(map.get(ans1)==0){
	            ts.remove(ans1);
	        }
	    for(Integer p:list.get(node)){
	        int nu = co[p];
	        //System.out.println(p+" -- "+node+" -- "+nu+" --- "+map.get(nu));

	        map.replace(nu,-1+map.get(nu));
	        if(map.get(nu)==0){
	            ts.remove(nu);
	        }
	    }
	    int re = ans1;
	    if(ts.floor(inf)!=null){
	        re+=ts.floor(inf);
	    }
	   // else{
	   //     re-=1;
	   // }

	   map.replace(ans1,+1+map.get(ans1));
	        ts.add(ans1);
	    for(Integer p:list.get(node)){
	        int nu = co[p];
	        map.replace(nu,+1+map.get(nu));
	        ts.add(nu);
	    }
	    //System.out.println(node+" --- "+re+" -- "+ans1);
	    res = Math.max(res,re-1);
	    for(Integer p:list.get(node)){
	        if(!vis[p]){
	            dfs2(p);
	        }
	    }

	}
	static int dfs(int node,int par){
	    for(Integer p:list.get(node)){
	        if(p==par)
	        continue;
	        dfs(p,node);
	        if(par!=-1){
	            res = Math.max(res,co[node]+co[par]-2);
	        }
	    }

	    //System.out.println(d1+" -- "+d2+" --- "+node+" -- "+par+" -- "+sz);
	    return 0;
	}
	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
		double nextDouble() {
			return Double.parseDouble(next());
		}
	}
}

Answer: 2


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

const ll MOD = 1e9 + 7;
const ll MAX_N = 5e5;

int main() {
    ll t;
    cin >> t;
    while (t--) {
        ll n;
        cin >> n;
        ll temp = n - 1;
        map<ll, multiset<ll>> m;

        // Read input and construct adjacency list
        while (temp--) {
            ll l, r;
            cin >> l >> r;
            m[l].insert(r);
            m[r].insert(l);
        }

        ll v = -1;
        ll maxx = 0;
        ll ans = 0;

        for (auto& i : m) {
            if (i.second.size() > maxx) {
                maxx = i.second.size();
                v = i.first;
            }
        }

        if (v != -1) {
            for (auto i : m[v]) {
                if (m.find(i) != m.end()) {
                    m[i].erase(v);
                }
            }
            m.erase(v);
            ans += maxx;
        }

        maxx = 0;
        v = -1;

        for (auto& i : m) {
            if (i.second.size() > maxx) {
                maxx = i.second.size();
                v = i.first;
            }
        }

        if (v != -1) {
            for (auto i : m[v]) {
                if (m.find(i) != m.end()) {
                    m[i].erase(v);
                }
            }
            m.erase(v);
            ans += maxx;
        }

        cout << ans - 1 << endl;
    }
    return 0;
}

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

const ll MOD = 1e9 + 7;
const ll MAX_N = 5e5;

int main() {
    ll t;
    cin >> t;
    while (t--) {
        ll n;
        cin >> n;
        ll temp = n - 1;
        map<ll, multiset<ll>> m;

        while (temp--) {
            ll l, r;
            cin >> l >> r;
            m[l].insert(r);
            m[r].insert(l);
        }
        // for(auto i :m){
        //     cout<<i.first<<":";
        //     for(auto j:i.second) cout<<j<<" ";
        //     cout<<endl;
        // }
        ll v = -1;
        ll maxx = 0;
        ll ans = 0;
        ll cnt = 0;

        for (auto& i : m) {
            if (i.second.size() > maxx) {
                maxx = i.second.size();
                v = i.first;
            }
        }
        for(auto i : m){
            if(i.second.size() == maxx){
                cnt++;
            }
        }
        if(cnt>=3){
            cout<<2*maxx - 1<<endl;
            continue;
        }
        if (v != -1) {
            for (auto i : m[v]) {
                if (m.find(i) != m.end()) {
                    m[i].erase(v);
                }
            }
            m.erase(v);
            ans += maxx;
        }

        maxx = 0;
        v = -1;

        for (auto& i : m) {
            if (i.second.size() > maxx) {
                maxx = i.second.size();
                v = i.first;
            }
        }

        if (v != -1) {
            for (auto i : m[v]) {
                if (m.find(i) != m.end()) {
                    m[i].erase(v);
                }
            }
            m.erase(v);
            ans += maxx;
        }
        // for(auto i :m){
        //     cout<<i.first<<":";
        //     for(auto j:i.second) cout<<j<<" ";
        //     cout<<endl;
        // }
        cout << ans - 1 << endl;
    }
    return 0;
}

Answer: 2


#include <bits/stdc++.h>
using namespace std;
#define Sort(a) sort(a.begin(),a.end());
#define all(a) a.begin(),a.end()
#define pb(x) push_back(x)
#define printvec(v)  for(auto x : v) cout<<x<<' ';cout<<endl;
#define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(__null);
#define input(a) {for(auto &x : a) cin>>x;}

typedef long long ll;
#define int long long int
const int mod=1e9+7;
const int N=2e5+7;
vector<int> graph[N];
vector<int> vis(N,0);
 struct val{
    int self=0,child=0;
 };
void solve(){

              //Start writing from here
              int n;cin>>n;
              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 best=0;
              vector<int> deg(n+1,0);
              for(int i=1;i<=n;i++) deg[i]=tree[i].size();
              multiset<int> mst;
              for(auto x: deg)  mst.insert(x);
              for(int node=1;node<=n;node++){
                   //if remove this vertex
                   //choose to remove the second vertex that is adj
                   mst.erase(mst.find(deg[node]));
                   for(auto x : tree[node]){
                        best=max(best,deg[node]+deg[x]-2);
                   }
                   //choose to remove the vertex not adj
                   vector<int> temp(1,deg[node]);
                   for(auto x : tree[node]){
                    temp.push_back(deg[x]);
                    mst.erase(mst.find(deg[x]));
                   }
                   best=max(best,*prev(mst.end())+deg[node]-1);
                    for(auto x: temp)   mst.insert(x);
              }
              cout<<best<<endl;

}
signed main()
{
  fastio()
    int t=1;
       //comment below line for single testcase
    cin >> t;
    while (t--)
    {

         solve();
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define Sort(a) sort(a.begin(),a.end());
#define all(a) a.begin(),a.end()
#define pb(x) push_back(x)
#define printvec(v)  for(auto x : v) cout<<x<<' ';cout<<endl;
#define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(__null);
#define input(a) {for(auto &x : a) cin>>x;}

typedef long long ll;
#define int long long int
const int mod=1e9+7;
const int N=2e5+7;
vector<int> graph[N];
vector<int> vis(N,0);
 struct val{
    int self=0,child=0;
 };
void solve(){

              //Start writing from here
              int n;cin>>n;
              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 best=0;
              vector<val> temp(n+1);
              function<int(int,int)> dfs1=[&](int node,int par)->int {
                int total=0;
                for(auto child : tree[node]){
                    if(child !=par){
                        total=max(dfs1(child,node),total);
                    }
                }
                temp[node].child=total;
                total=max(total,(int)tree[node].size());
                temp[node].self=total;
                return total;
              };
              dfs1(1,0);
              function<void(int,int)> dfs=[&](int node,int par)->void {
                for(auto child : tree[node]){
                    if(child !=par){
                        best=max(best,(int)(temp[child].child+tree[node].size()-1));
                        best=max(best,(int)(tree[node].size()+tree[child].size()-2));
                        dfs(child,node);
                    }
                }
              };
              dfs(1,0);
              //non adjacent
              cout<<best<<endl;

}
signed main()
{
  fastio()
    int t=1;
       //comment below line for single testcase
    cin >> t;
    while (t--)
    {

         solve();
    }
    return 0;
}

Answer: 1


#include <bits/stdc++.h>

#define fastio                        \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL)

#define endl "\n"
#define fraction()                \
    cout.unsetf(ios::floatfield); \
    cout.precision(10);           \
    cout.setf(ios::fixed, ios::floatfield);
#define mem(a, b) memset(a, b, sizeof(a))

using namespace std;

typedef long long ll;
typedef double dl;
class tree
{
    vector<vector<int>> adj;
    // map<int,int> size;
    int n;

public:
    tree(int n) : n(n)
    {
        adj.resize(n + 1);
        // size.resize(n+1);
        input();
    }
    void input()
    {
        for (int i = 1; i < n; i++)
        {
            int u, v;
            cin >> u >> v;
            adj[u].push_back(v);
            adj[v].push_back(u);
            // size[u]++;
            // size[v]++;
        }
        solve();
    }

    void solve()
    {

        ll ans = 0;
        vector<pair<int, int>> v;
        for (int i = 1; i < adj.size(); i++)// 1 indexed 1->n
        {
            v.push_back({adj[i].size(), i});
        }
        // cout<<v.size()<< " "<<n<<endl;
        if (v.size() <= 2)
        {
            cout << 0 << endl;
            return;
        }
        sort(v.begin(), v.end());
        reverse(v.begin(), v.end());
        int ele1 = v[0].second; // ele with max child
        ans = adj[ele1].size();

        map<int, bool> m_connected_to_ele1;
        for (int i = 0; i < adj[ele1].size(); i++)
        {
            m_connected_to_ele1[adj[ele1][i]] = true;
        }
        // cout<<ans<<endl;// 3 hoiche
        // ll max_sec_ans = 0;//ninus o hoite pare
        ll max_sec_ans = - INFINITY;
        for (int i = 1; i < v.size(); i++)
        {
        //     cout<<v[i].first<<" v v "<<v[i].second<<endl;
        //     cout<<m_connected_to_ele1[v[i].second]<<endl;
            ll temp = v[i].first - 1;
            // if (m_connected_to_ele1[temp])
            /// prob
            if(m_connected_to_ele1[v[i].second])
            {
                temp--;
            }
            // cout<<temp<<" "<<max_sec_ans<<endl;
            max_sec_ans = max(max_sec_ans, temp);

            // ansmax
        }
        cout<<ans+max_sec_ans<<endl;

        // if(size.size()<=2){
        //     cout<<0<<endl;
        //     return;
        // }
        // int ele1,ele2;
        // auto it=size.rbegin();
        // ele1=it->first;
        // it++;
        // ele2=it->second;

        // cout<<ele1<<" "<<ele2<<endl;

        // int ans=0;
        // ans+=adj[ele1].size();
        // ans+=adj[ele2].size()-1;
        // for(int i=0;i<adj[ele1].size();i++){
        //     if(adj[ele1][i]==ele2){
        //         ans--;
        //         break;
        //     }
        // }
        // cout << ans << endl;
    }
};

void solve(ll tc)
{
    int n;
    cin >> n;
    tree t(n);
}

int main()
{
    fastio;
    ll t = 1;
    cin >> t;

    for (int i = 1; i <= t; i++)
    {
        solve(i);
    }
    return 0;
}

#include <bits/stdc++.h>

#define fastio                        \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL)

#define endl "\n"
#define fraction()                \
    cout.unsetf(ios::floatfield); \
    cout.precision(10);           \
    cout.setf(ios::fixed, ios::floatfield);
#define mem(a, b) memset(a, b, sizeof(a))

using namespace std;

typedef long long ll;
typedef double dl;
class tree
{
    vector<vector<ll>> adj;
    // map<ll,ll> size;
    ll n;

public:
    tree(ll n) : n(n)
    {
        adj.resize(n + 1);
        // size.resize(n+1);
        input();
    }
    void input()
    {
        for (ll i = 1; i < n; i++)
        {
            ll u, v;
            cin >> u >> v;
            adj[u].push_back(v);
            adj[v].push_back(u);
            // size[u]++;
            // size[v]++;
        }
        solve();
    }

    ll ret(vector<pair<ll,ll>> &v, int ii)
    {
        ll ans = 0;

        ll ele1 = v[ii].second; // ele with max child
        ans = adj[ele1].size();

        map<ll, bool> m_connected_to_ele1;
        for (ll i = 0; i < adj[ele1].size(); i++)
        {
            m_connected_to_ele1[adj[ele1][i]] = true;
        }
        // cout<<ans<<endl;// 3 hoiche
        // ll max_sec_ans = 0;//ninus o hoite pare
        ll max_sec_ans = -INFINITY;
        for (ll i = 0; i < v.size(); i++)
        {
            if (i == ii)
                continue;
            ll temp = v[i].first - 1;
            // if (m_connected_to_ele1[temp])
            /// prob
            if (m_connected_to_ele1[v[i].second])
            {
                temp--;
            }
            // cout<<temp<<" "<<max_sec_ans<<endl;
            max_sec_ans = max(max_sec_ans, temp);

            // ansmax
        }
        ans += max_sec_ans;
        return ans;
    }

    void solve()
    {

        ll ans = 0;
        vector<pair<ll, ll>> v;
        for (ll i = 1; i < adj.size(); i++) // 1 indexed 1->n
        {
            v.push_back({adj[i].size(), i});
        }
        // cout<<v.size()<< " "<<n<<endl;
        if (v.size() <= 2)
        {
            cout << 0 << endl;
            return;
        }
        sort(v.begin(), v.end());
        reverse(v.begin(), v.end());
        ans = max(ans, ret(v, 0));
        ans = max(ans, ret(v, 1));
        ans = max(ans, ret(v, 2));

        cout << ans << endl;

        // if(size.size()<=2){
        //     cout<<0<<endl;
        //     return;
        // }
        // ll ele1,ele2;
        // auto it=size.rbegin();
        // ele1=it->first;
        // it++;
        // ele2=it->second;

        // cout<<ele1<<" "<<ele2<<endl;

        // ll ans=0;
        // ans+=adj[ele1].size();
        // ans+=adj[ele2].size()-1;
        // for(ll i=0;i<adj[ele1].size();i++){
        //     if(adj[ele1][i]==ele2){
        //         ans--;
        //         break;
        //     }
        // }
        // cout << ans << endl;
    }
};

void solve(ll tc)
{
    ll n;
    cin >> n;
    tree t(n);
}

int main()
{
    fastio;
    ll t = 1;
    cin >> t;

    for (ll i = 1; i <= t; i++)
    {
        solve(i);
    }
    return 0;
}

Answer: 2


#include <bits/stdc++.h>
using namespace std;
#define int long long
#define vi vector<int>
#define pb push_back
#define all(x) (x).begin(), (x).end()

void solve() {
    int n;
    cin >> n;
    vi adj[n + 1];
    vi f(n + 1, 0);

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

    if (n <= 2) {
        cout << 0 << endl;
        return;
    }
    if (n == 3) {
        cout << 1 << endl;
        return;
    }

    int ind = max_element(all(f)) - f.begin();
    int ans = f[ind];

    int ct = 0;
    for (auto it : adj[ind]) {
        if (f[it] == ans)
            ct++;
    }

    if (ct >= 2) {
        cout << (ans + ans - 1) << endl;
        return;
    }

    for (auto it : adj[ind]) {
        f[it]--;
    }
    f[ind] = 0;

    int ind1 = max_element(all(f)) - f.begin();
    ans += (f[ind1] - 1);
    cout << ans << endl;
}

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

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define vi vector<int>
#define pb push_back
#define all(x) (x).begin(), (x).end()

void solve() {
    int n;
    cin >> n;
    vi adj[n + 1];
    vi f(n + 1, 0);

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

    if (n <= 2) {
        cout << 0 << endl;
        return;
    }
    // if (n == 3) {
    //     cout << 1 << endl;
    //     return;
    // }

    int mx = max_element(f.begin() + 1, f.end()) - f.begin();
    // cout<<mx<<endl;
    vi deg(n + 1);
    for (int i = 1; i <= n; i++) {
        deg[i] = adj[i].size();
    }

    int temp = deg[mx];

    for (auto ele : adj[mx]) {
        deg[ele]--;
    }

    deg[mx] = 0;
    //  for(int i=1;i<=n;i++ )
    // {
    //     cout<<i<<"->"<<deg[i]<<endl;
    // }
    int sc_mx = max_element(deg.begin() + 1, deg.end()) - deg.begin();
    // cout<<sc_mx<<endl;

    cout << deg[sc_mx] + temp - 1 << endl;
}

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

Answer: 1


// Name-Anshu Raj Jaiswal
// Scholar id-2212172
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define pb push_back
#define ff first
#define ss second
#define mpq priority_queue<ll,vector<ll>,greater<ll>>
#define mpqp priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>>
#define Mpq priority_queue<ll>
#define Mpqp priority_queue<pair<ll,ll>>
#define all(x) (x).begin(), (x).end()
const ll MOD=998244353;
const ll N=200000;
ll ceil(ll a,ll b){return (a+b-1)/b;}
void solve()
{
 ll n;
 cin>>n;
 vector<ll>temp(n+1,0);
 vector<ll>temp2(n+1,0);
 vector<pair<ll,ll>>arr(n-1);
 map<ll,ll>my;
 for(ll i=0;i<n-1;i++)
 {
  ll u,v;
  cin>>u>>v;
  temp[u]++;temp[v]++;
  arr[i]={u,v};
 }
 ll ans=0;
 ll in=-1;
 for(ll i=1;i<=n;i++)
 {
   if(temp[i]>ans)
   {
    ans=temp[i];
    in=i;
   }
   my[temp[i]]++;
 }
 if(my[ans]>2)
 {
  cout<<2*ans-1<<endl;
  return;
 }
 ans--;
 for(ll i=0;i<n-1;i++)
 {
  ll u=arr[i].ff,v=arr[i].ss;
  if(u==in || v==in)
  continue;
  temp2[u]++;temp2[v]++;
 }
 ll pi=0;
 for(ll i=1;i<=n;i++)
 pi=max(pi,temp2[i]);
 ans+=pi;
 cout<<ans<<endl;
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);cout.tie(NULL);
  ll t;
  cin>>t;
  while(t--)
  {
	  solve();
  }
  return 0;
}

// Name-Anshu Raj Jaiswal
// Scholar id-2212172
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define pb push_back
#define ff first
#define ss second
#define mpq priority_queue<ll,vector<ll>,greater<ll>>
#define mpqp priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>>
#define Mpq priority_queue<ll>
#define Mpqp priority_queue<pair<ll,ll>>
#define all(x) (x).begin(), (x).end()
const ll MOD=998244353;
const ll N=200000;
ll ceil(ll a,ll b){return (a+b-1)/b;}
ll pi=0;
void dfs(ll node,vector<ll>&vis,vector<ll>&temp2,vector<vector<ll>>&adj)
{
  vis[node]=1;
  for(auto it:adj[node])
  {
    if(!vis[it])
    {
      temp2[node]++;
      temp2[it]++;
      dfs(it,vis,temp2,adj);
    }
  }
  return;
}
void solve()
{
 ll n;
 cin>>n;
 vector<vector<ll>>adj(n+1);
 vector<ll>temp(n+1,0);
 vector<pair<ll,ll>>arr(n-1);
 for(ll i=0;i<n-1;i++)
 {
  ll u,v;
  cin>>u>>v;
  temp[u]++;temp[v]++;
  arr[i]={u,v};
 }
 ll ans=0;
 ll in=-1;
 for(int i=0;i<n;i++)
 {
   if(temp[i]>ans)
   {
    ans=temp[i];
    in=i;
   }
 }
 ans--;
 for(ll i=0;i<n-1;i++)
 {
  ll u=arr[i].ff,v=arr[i].ss;
  if(u==in || v==in)continue;
  adj[u].pb(v);adj[v].pb(u);
 }
 vector<ll>vis(n+1,0);
 vector<ll>temp2(n+1,0);
 for(ll i=0;i<n;i++)
 {
   if(!vis[i])
   {
      dfs(i,vis,temp2,adj);
   }
 }
 ll pi=0;
 for(ll i=0;i<n;i++)
 {
   pi=max(pi,temp2[i]);
 }
 ans+=pi;
 cout<<ans<<endl;
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);cout.tie(NULL);
  ll t;
  cin>>t;
  while(t--)
  {
	  solve();
  }
  return 0;
}

Answer: 1