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

#define int long long int
#define pi pair<int,int>
#define all(n) n.begin(), n.end()
#define rall(n) n.begin(), n.end(), greater<int>()
#define fr(i,a,b,c) for(int i=a;i<b;i+=c)
#define rfr(i,a,b,c) for(int i=a;i>=b;i-=c)
#define pb push_back
// Input Functions
template<typename T>std::vector<T> input(int n) {std::vector<T> v(n);for (int i = 0; i < n; ++i) {std::cin >> v[i];}return v;}
template<typename A, typename B>std::vector<std::pair<A, B>> input(int n) {std::vector<std::pair<A, B>> v;for (int i = 0; i < n; ++i) {A first;B second;std::cin >> first >> second;v.emplace_back(first, second);}return v;}
template<typename T>std::vector<std::vector<T>> input(int n, int m) {std::vector<std::vector<T>> vv(n, std::vector<T>(m));for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {std::cin >> vv[i][j];}}return vv;}

// Debugging
template<typename T>void printContainer(const std::vector<T>& v) {std::cout << "Vector : ";std::cout << "[ ";for (const T& value : v) {std::cout << value << " ";}std::cout << "]" << std::endl;}
template<typename A, typename B>void printContainer(const std::vector<std::pair<A, B>>& v) {std::cout << "Vector of Pairs: ";std::cout << "[ ";for (const auto& p : v) {std::cout << "(" << p.first << ", " << p.second << ") ";}std::cout << "]" << std::endl;}
template<typename T>void printContainer(const std::vector<std::vector<T>>& vv) {std::cout << "Vector of Vectors:" << std::endl;for (const auto& row : vv) {for (const T& value : row) {std::cout << value << " ";}std::cout << std::endl;}}
template <typename T1, typename T2> void printContainer(const map<T1, T2>& m) { std::cout << "Map : ";cout << "["; for (auto it = m.begin(); it != m.end(); ++it) { if (it != m.begin()) cout << ", "; cout << "["<<it->first << "->" << it->second<<"]"; } cout << "]"<<endl; }
template<typename T>void printContainer(const std::priority_queue<T>& pq) {std::priority_queue<T> temp = pq;std::cout << "Priority Queue: ";while (!temp.empty()) {std::cout << temp.top() << " ";temp.pop();}std::cout << std::endl;}
template <typename T> void printContainer(stack<T> stk) { cout << "["; while (!stk.empty()) { if (stk.size() != sz(stk)) cout << ", "; cout << stk.top(); stk.pop(); } cout << "]"; }
template<typename T> void printContainer(const std::queue<T>& q) {std::queue<T> temp = q; std::cout << "Queue: ";while (!temp.empty()) {std::cout << temp.front() << " ";temp.pop();}   std::cout << std::endl;}
template<typename A, typename B>void printContainer(const std::queue<std::pair<A, B>>& q) {std::queue<std::pair<A, B>> temp = q;     std::cout << "Queue of Pairs: ";while (!temp.empty()) {std::cout << "(" << temp.front().first << ", " << temp.front().second << ") ";temp.pop();}std::cout << std::endl;}
template<typename A, typename B>void printContainer(const std::stack<std::pair<A, B>>& s) {std::stack<std::pair<A, B>> temp = s; std::cout << "Stack of Pairs: ";while (!temp.empty()) {std::cout << "(" << temp.top().first << ", " << temp.top().second << ") ";temp.pop();}std::cout << std::endl;}

// Printing
template<typename T>void print(const std::vector<T>& v) {for (const T& value : v) {std::cout << value << " ";}std::cout << endl;}
template<typename T>void print(const std::vector<std::vector<T>>& vv) {for (const auto& row : vv) {for (const T& value : row) {std::cout << value << " ";}std::cout << std::endl;}}

int mod_mul(int a, int b, int m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
vector<int>factorial(int n,int m){vector<int>v(n);v[0]=1;for(int i=1;i<n;i++){v[i]=mod_mul(v[i-1],i,m);}return v;}
int powerof2(int a){return a && !(a&a-1);}
void printBinary(int num){for(int i=10;i>=0;i--){cout<<((num>>i)&1);}}
int N = 1e6;
vector<int> isPrime(N+1,1);void prime(){isPrime[0] = isPrime[1]=false;for(int i=2;i<=N;i++){if(isPrime[i]){for(int j=2*i;j<=N;j+=i){isPrime[j] = 0;}}}}
vector<int>divisor(int n){vector<int>res;for (int i=1; i<=sqrt(n); i++){if (n%i == 0){if (n/i == i) res.push_back(i);else{res.push_back(i);res.push_back(n/i);} }}return res;}
bool cmp(pair<int, int> x, pair<int, int> y){if (x.first != y.first)return x.first < y.first; else return x.second < y.second; }
int meraceil(int a,int b){if(a%b==0) return a/b;return (a/b)+1;}
int power(int x,int y,int p){int res=1;while(y>0){if(y&1)res = (res * x)%p;y = y >> 1;x = (x * x)%p;}return (res%p);}
vector<int> primeDivisors(int val){vector<int> res;if(val%2==0) res.pb(2);while(val%2==0){val/=2;}for(int j=3;j<=sqrt(val);j+=2){if(val%j==0) res.pb(j);while(val%j==0){val/=j;}}if(val>2) res.pb(val);return res;}

//-------------------------CODE----------------------
void Shiremonoga(){
    int n;
    cin >> n;
    set<int> adj[n+1];
    fr(i,0,n-1,1){
        int u, v;
        cin >> u >> v;
        adj[u].insert(v);
        adj[v].insert(u);
    }
    int mx = INT_MIN, mx2 = INT_MIN;
    map<int,vector<int>> mp;
    fr(i,1,n+1,1){
        int sz = adj[i].size();
        mp[sz].push_back(i);
        if(sz >= mx){
            mx2 = mx, mx = sz;
        }
        else if(sz > mx2) mx2 = sz;
    }
    int ans = INT_MIN;
    for(auto &mxNode : mp[mx]){
        for(auto &mxNode2 : mp[mx2]){
            if(mxNode2==mxNode) continue;
            int curr = 0;
            if(adj[mxNode].find(mxNode2) != adj[mxNode].end()){
                curr = mx2-2;
            }else{
                curr = mx2-1;
            }
            ans = max(ans, mx+curr);
        }
    }
    cout << ans << endl;

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

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

#define int long long int
#define pi pair<int,int>
#define all(n) n.begin(), n.end()
#define rall(n) n.begin(), n.end(), greater<int>()
#define fr(i,a,b,c) for(int i=a;i<b;i+=c)
#define rfr(i,a,b,c) for(int i=a;i>=b;i-=c)
#define pb push_back
// Input Functions
template<typename T>std::vector<T> input(int n) {std::vector<T> v(n);for (int i = 0; i < n; ++i) {std::cin >> v[i];}return v;}
template<typename A, typename B>std::vector<std::pair<A, B>> input(int n) {std::vector<std::pair<A, B>> v;for (int i = 0; i < n; ++i) {A first;B second;std::cin >> first >> second;v.emplace_back(first, second);}return v;}
template<typename T>std::vector<std::vector<T>> input(int n, int m) {std::vector<std::vector<T>> vv(n, std::vector<T>(m));for (int i = 0; i < n; ++i) {for (int j = 0; j < m; ++j) {std::cin >> vv[i][j];}}return vv;}

// Debugging
template<typename T>void printContainer(const std::vector<T>& v) {std::cout << "Vector : ";std::cout << "[ ";for (const T& value : v) {std::cout << value << " ";}std::cout << "]" << std::endl;}
template<typename A, typename B>void printContainer(const std::vector<std::pair<A, B>>& v) {std::cout << "Vector of Pairs: ";std::cout << "[ ";for (const auto& p : v) {std::cout << "(" << p.first << ", " << p.second << ") ";}std::cout << "]" << std::endl;}
template<typename T>void printContainer(const std::vector<std::vector<T>>& vv) {std::cout << "Vector of Vectors:" << std::endl;for (const auto& row : vv) {for (const T& value : row) {std::cout << value << " ";}std::cout << std::endl;}}
template <typename T1, typename T2> void printContainer(const map<T1, T2>& m) { std::cout << "Map : ";cout << "["; for (auto it = m.begin(); it != m.end(); ++it) { if (it != m.begin()) cout << ", "; cout << "["<<it->first << "->" << it->second<<"]"; } cout << "]"<<endl; }
template<typename T>void printContainer(const std::priority_queue<T>& pq) {std::priority_queue<T> temp = pq;std::cout << "Priority Queue: ";while (!temp.empty()) {std::cout << temp.top() << " ";temp.pop();}std::cout << std::endl;}
template <typename T> void printContainer(stack<T> stk) { cout << "["; while (!stk.empty()) { if (stk.size() != sz(stk)) cout << ", "; cout << stk.top(); stk.pop(); } cout << "]"; }
template<typename T> void printContainer(const std::queue<T>& q) {std::queue<T> temp = q; std::cout << "Queue: ";while (!temp.empty()) {std::cout << temp.front() << " ";temp.pop();}   std::cout << std::endl;}
template<typename A, typename B>void printContainer(const std::queue<std::pair<A, B>>& q) {std::queue<std::pair<A, B>> temp = q;     std::cout << "Queue of Pairs: ";while (!temp.empty()) {std::cout << "(" << temp.front().first << ", " << temp.front().second << ") ";temp.pop();}std::cout << std::endl;}
template<typename A, typename B>void printContainer(const std::stack<std::pair<A, B>>& s) {std::stack<std::pair<A, B>> temp = s; std::cout << "Stack of Pairs: ";while (!temp.empty()) {std::cout << "(" << temp.top().first << ", " << temp.top().second << ") ";temp.pop();}std::cout << std::endl;}

// Printing
template<typename T>void print(const std::vector<T>& v) {for (const T& value : v) {std::cout << value << " ";}std::cout << endl;}
template<typename T>void print(const std::vector<std::vector<T>>& vv) {for (const auto& row : vv) {for (const T& value : row) {std::cout << value << " ";}std::cout << std::endl;}}

int mod_mul(int a, int b, int m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
vector<int>factorial(int n,int m){vector<int>v(n);v[0]=1;for(int i=1;i<n;i++){v[i]=mod_mul(v[i-1],i,m);}return v;}
int powerof2(int a){return a && !(a&a-1);}
void printBinary(int num){for(int i=10;i>=0;i--){cout<<((num>>i)&1);}}
int N = 1e6;
vector<int> isPrime(N+1,1);void prime(){isPrime[0] = isPrime[1]=false;for(int i=2;i<=N;i++){if(isPrime[i]){for(int j=2*i;j<=N;j+=i){isPrime[j] = 0;}}}}
vector<int>divisor(int n){vector<int>res;for (int i=1; i<=sqrt(n); i++){if (n%i == 0){if (n/i == i) res.push_back(i);else{res.push_back(i);res.push_back(n/i);} }}return res;}
bool cmp(pair<int, int> x, pair<int, int> y){if (x.first != y.first)return x.first < y.first; else return x.second < y.second; }
int meraceil(int a,int b){if(a%b==0) return a/b;return (a/b)+1;}
int power(int x,int y,int p){int res=1;while(y>0){if(y&1)res = (res * x)%p;y = y >> 1;x = (x * x)%p;}return (res%p);}
vector<int> primeDivisors(int val){vector<int> res;if(val%2==0) res.pb(2);while(val%2==0){val/=2;}for(int j=3;j<=sqrt(val);j+=2){if(val%j==0) res.pb(j);while(val%j==0){val/=j;}}if(val>2) res.pb(val);return res;}

//-------------------------CODE----------------------
void Shiremonoga(){
    int n;
    cin >> n;
    set<int> adj[n+1];
    fr(i,0,n-1,1){
        int u, v;
        cin >> u >> v;
        adj[u].insert(v);
        adj[v].insert(u);
    }
    int mx = INT_MIN, mx2 = INT_MIN;
    map<int,vector<int>> mp;
    fr(i,1,n+1,1){
        int sz = adj[i].size();
        mp[sz].push_back(i);
        if(sz >= mx){
            mx2 = mx, mx = sz;
        }
        else if(sz > mx2) mx2 = sz;
    }
    int ans = INT_MIN;
    for(auto &mxNode : mp[mx]){
        bool chk = false;
        for(auto &mxNode2 : mp[mx2]){
            if(mxNode2==mxNode) continue;
            int curr = 0;
            if(adj[mxNode].find(mxNode2) != adj[mxNode].end()){
                curr = mx2-2;
                ans = max(ans, mx+curr);
            }else{
                curr = mx2-1;
                ans = max(ans, mx+curr);
                chk = true;
                break;
            }
        }
        if(chk) break;
    }
    cout << ans << endl;

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

Answer: 2


#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
ll n;

void check(ll v, vector<set<ll>> &adj){
    for(ll i=1; i<adj.size(); i++){
        if(adj[i].find(v)!=adj[i].end()){
            adj[i].erase(v);
        }
    }
}

void dfs(ll node, vector<set<ll>> &adj, vector<ll> &vis){
    vis[node]=1;
    for(auto i: adj[node]){
        if(vis[i]) continue;
        dfs(i,adj,vis);
    }
}

int main(){
	int t;
	cin>>t;
	while(t--){
		cin>>n;
        ll ans1,ans2;
        ll maxi=0;
		vector<set<ll>> adj(n+1);
        set<pair<ll,ll>> st;
        for(ll i=0; i<n-1; i++){
            ll u,v;
            cin>>u>>v;
            st.insert({u,v});
            adj[u].insert(v);
            adj[v].insert(u);
        }

        for(ll i=1; i<=n; i++){
            if(adj[i].size()>maxi){
                maxi=adj[i].size();
            }
        }

        vector<ll> v;
        for(ll i=1; i<=n; i++){
            if(adj[i].size()==maxi) v.push_back(i);
        }

        if(v.size()>2){
            ll x=v[0],y=v[1],z=v[2];
            if(st.find({x,y})==st.end()){
                ans1=x;
                ans2=y;
            }
            if(st.find({y,z})==st.end()){
                ans1=y;
                ans2=z;
            }
            if(st.find({x,z})==st.end()){
                ans1=x;
                ans2=z;
            }
            check(ans1,adj);
            check(ans2,adj);
        }
        if(v.size()==2){
            ans1=v[0],ans2=v[1];
            check(ans1,adj);
            check(ans2,adj);
        }
        if(v.size()==1){
            ans1=v[0];
            check(ans1,adj);
            maxi=0;
            for(ll i=1; i<=n; i++){
                if(i==ans1) continue;
                if(adj[i].size()>maxi){
                    maxi=adj[i].size();
                }
            }
            for(ll i=1; i<=n; i++){
                if(adj[i].size()==maxi) ans2=i;
            }
            check(ans2,adj);
        }

        ll ans=0;
        vector<ll> vis(n+1,0);
        vis[ans1]=1;
        vis[ans2]=1;
        for(ll i=1; i<=n; i++){
            if(!vis[i]){
                dfs(i,adj,vis);
                ans++;
            }
        }

        cout<<ans<<endl;
	}
}

#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
ll n;

void check(ll v, vector<set<ll>> &adj){
    for(ll i=1; i<adj.size(); i++){
        if(adj[i].find(v)!=adj[i].end()){
            adj[i].erase(v);
        }
    }
}

void dfs(ll node, vector<set<ll>> &adj, vector<ll> &vis){
    vis[node]=1;
    for(auto i: adj[node]){
        if(vis[i]) continue;
        dfs(i,adj,vis);
    }
}

int main(){
	int t;
	cin>>t;
	while(t--){
		cin>>n;
        ll ans1,ans2;
        ll maxi=0;
		vector<set<ll>> adj(n+1);
        set<pair<ll,ll>> st;
        for(ll i=0; i<n-1; i++){
            ll u,v;
            cin>>u>>v;
            st.insert({u,v});
            adj[u].insert(v);
            adj[v].insert(u);
        }

        for(ll i=1; i<=n; i++){
            if(adj[i].size()>maxi){
                maxi=adj[i].size();
            }
        }

        vector<ll> v;
        for(ll i=1; i<=n; i++){
            if(adj[i].size()==maxi) v.push_back(i);
        }

        if(v.size()>2){
            ll x=v[0],y=v[1],z=v[2];
            if(st.find({x,y})==st.end() && st.find({y,x})==st.end()){
                ans1=x;
                ans2=y;
            }
            if(st.find({y,z})==st.end() && st.find({z,y})==st.end()){
                ans1=y;
                ans2=z;
            }
            if(st.find({x,z})==st.end() && st.find({z,x})==st.end()){
                ans1=x;
                ans2=z;
            }
        }
        else if(v.size()==2){
            ans1=v[0],ans2=v[1];
        }
        else{
            ans1=v[0];
            check(ans1,adj);
            maxi=0;
            vector<ll> temp;
            for(ll i=1; i<=n; i++){
                if(i==ans1) continue;
                if(adj[i].size()>=maxi){
                    maxi=adj[i].size();
                }
            }
            for(ll i=1; i<=n; i++){
                if(adj[i].size()==maxi && i!=ans1) temp.push_back(i);
            }
            ans2=temp[0];
            for(ll i=0; i<temp.size(); i++){
                if(st.find({ans1,temp[i]})==st.end() && st.find({temp[i],ans1})==st.end()){
                    ans2=temp[i];
                    break;
                }
            }
        }
        check(ans1,adj);
        check(ans2,adj);

        ll ans=0;
        vector<ll> vis(n+1,0);
        vis[ans1]=1;
        vis[ans2]=1;
        for(ll i=1; i<=n; i++){
            if(!vis[i]){
                dfs(i,adj,vis);
                ans++;
            }
        }

        cout<<ans<<endl;
	}
}

Answer: 2


#include<bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
#define ll long long
const int inf=1e9;
const ll inff=1e18;
using i128=__int128;

void solve() {
    int n;
    cin>>n;
    vector<int> deg(n);
    vector<vector<int>> adj(n);
    for(int i=0;i<n-1;i++){
        int x,y;
        cin>>x>>y;
        x--,y--;
        deg[x]++,deg[y]++;
        adj[x].emplace_back(y);
        adj[y].emplace_back(x);
    }
    auto cmp=[&](int x,int y){
        return deg[x]<deg[y];
    };
    priority_queue<int,vector<int>,decltype(cmp)> pq(cmp);
    for(int i=0;i<n;i++){
        pq.push(i);
    }
    // int x=pq.top();
    // pq.pop();
    if(n==2){
        cout<<0<<'\n';
        return;
    }
    int a=pq.top();
    pq.pop();
    int b=pq.top();
    pq.pop();
    int c=pq.top();
    pq.pop();
    if(deg[a]==deg[b] && deg[b]==deg[c]){
        cout<<deg[a]*2-1<<'\n';
        return;
    }
    pq.push(b);
    pq.push(c);
    for(int y:adj[a]){
        deg[y]--;
    }
    int y=pq.top();
    int ans=deg[a]+deg[y]-1;
    // for(int v:adj[x]){
    //     ans=max(ans,deg[v]==0?deg[x]-1:deg[v]==1?deg[x]:deg[x]+deg[v]);
    // }
    cout<<ans<<"\n";
}

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

#include<bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
#define ll long long
const int inf=1e9;
const ll inff=1e18;
using i128=__int128;

void solve() {
    int n;
    cin>>n;
    vector<int> deg(n);
    vector<vector<int>> adj(n);
    for(int i=0;i<n-1;i++){
        int x,y;
        cin>>x>>y;
        x--,y--;
        deg[x]++,deg[y]++;
        adj[x].emplace_back(y);
        adj[y].emplace_back(x);
    }
    vector<int> it(n);
    iota(it.begin(),it.end(),0);
    sort(it.begin(),it.end(),[&](int x,int y){
        return deg[x]>deg[y];
    });
    if(n==2){
        cout<<0<<'\n';
        return;
    }
    int a=it[0],b=it[1],c=it[2];
    if(deg[a]==deg[b] && deg[b]==deg[c]){
        cout<<deg[a]*2-1<<'\n';
        return;
    }
    for(int y:adj[a]){
        deg[y]--;
    }
    sort(it.begin()+1,it.end(),[&](int x,int y){
        return deg[x]>deg[y];
    });
    cout<<deg[a]+deg[it[1]]-1<<'\n';
    // auto cmp=[&](int x,int y){
    //     return deg[x]<deg[y];
    // };
    // set<int,decltype(cmp)> st(cmp);
    // for(int i=0;i<n;i++){
    //     st.insert(i);
    // }
    // if(n==2){
    //     cout<<0<<'\n';
    //     return;
    // }
    // int a=*st.begin();
    // st.erase(st.begin());
    // int b=*st.begin();
    // st.erase(st.begin());
    // int c=*st.begin();
    // st.erase(st.begin());
    // if(deg[a]==deg[b] && deg[b]==deg[c]){
    //     cout<<deg[a]*2-1<<'\n';
    //     return;
    // }
    // st.insert(b);
    // st.insert(c);
    // for(int y:adj[a]){
    //     deg[y]--;
    // }
    // int y=*st.begin();
    // // while(pq.size()){
    // //     int y=pq.top();
    // //     cout<<y<<' '<<deg[y]<<'\n';
    // //     pq.pop();
    // // }
    // cout<<deg[a]+deg[y]-1<<"\n";
}

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

Answer: 2


#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<typename T>
using orderedSet = tree<T , null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T>
using orderedMultiset = tree<T , null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k) -> iterator at k
// order_of_key(k) -> number of items that are strictly smaller than k

#define FASTIO() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD1 1000000007
#define MOD9 998244353
#define INF 1e9
#define INF1 1e18
#define endl "\n"
#define pb push_back
#define ppb pop_back
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define all(x) (x).begin(), (x).end()
#define lb lower_bound
#define ub upper_bound
#define fcout cout<<fixed<<setprecision(10)
#define YES  cout<<"YES"<<endl
#define NO cout<<"NO"<<endl

typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;

// ---------------------------------- DEFINES ---------------------------------------
typedef vector <int> vi;
typedef vector <ll> vll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <vector <int> > vvi;
typedef vector <pii> vpii;
typedef vector <pll> vpll;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T, vector<T>, greater<T>>;
// ----------------------------------------------------------------------------------

// ---------------------------------- OPERATOR OVERLOADING ---------------------------------------
template<typename T>
istream& operator>>(istream &istream, vector<T> &v) {for (auto &x : v)cin >> x; return istream;}
template<typename T>
ostream& operator<<(ostream &ostream, const vector<T> &v) { for (auto &x : v) cout << x << " "; return ostream; }
template<typename T1, typename T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.ff >> p.ss); }
template<typename T1, typename T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.ff << " " << p.ss); }
template<typename T1, typename T2>
istream& operator>>(istream &istream, vector<pair<T1, T2>> &v) {for (auto &x : v)cin >> x; return istream;}
template<typename T1, typename T2>
ostream& operator<<(ostream &ostream, const vector<pair<T1, T2>> &v) { for (auto &x : v) cout << x << endl; return ostream; }
template<typename T>
istream& operator>>(istream &istream, vector<vector<T>> &v) {for (auto &x : v)cin >> x; return istream;}
template<typename T>
ostream& operator<<(ostream &ostream, const vector<vector<T>> &v) { for (auto &x : v) cout << x << endl; return ostream; }
// ------------------------------------------------------------------------------------------------

// ------------------------------------------ DEBUG ------------------------------------------------
#ifndef ONLINE_JUDGE
#define debug(x...) cerr <<__func__<<":"<<__LINE__<<" [" << #x << "] = "; _print(x); cerr << endl;
#define HERE cerr <<__func__<<":"<<__LINE__<<" [ here ] "; cerr << endl;
#else
#define debug(x...)
#endif

void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}

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 << "]";}
template <class T> void _print(vector <vector <T> > v) {cerr << "{ "; for (vector<T> i : v) {cerr << "[ "; for (T j : i) {_print(j); cerr << " ";}; cerr << "] ";} cerr << "}";}
template <class T, class V> void _print(vector < pair <T , V> > vp) {cerr << "{ "; for (pair<T, V> i : vp) {cerr << "[ "; "{"; _print(i.ff); cerr << ","; _print(i.ss); cerr << " ] ";} cerr << "}";}
template <class T> void _print(stack <T> st) {cerr << "[ "; while (!st.empty()) {_print(st.top()); st.pop(); cerr << " ";} cerr << "]";}
template <class T> void _print(queue <T> q) {cerr << "[ "; while (!q.empty()) {_print(q.front()); q.pop(); cerr << " ";} cerr << "]";}
template <class T> void _print(deque <T> dq) {cerr << "[ "; while (!dq.empty()) {_print(dq.front()); dq.pop_front(); cerr << " ";} cerr << "]";}
template <class T> void _print(PQ <T> pq) {cerr << "[ "; while (!pq.empty()) {_print(pq.top()); pq.pop(); cerr << " ";} cerr << "]";}
template <class T> void _print(QP <T> pq) {cerr << "[ "; while (!pq.empty()) {_print(pq.top()); pq.pop(); cerr << " ";} cerr << "]";}
//---------------------------------------------------------------------------------------------------

void solve() {

	//solution starts from here
	int n;
	cin>>n;

	vvi adj(n);
	vi deg(n);

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

	set<pii> st;
	for(int i=0;i<n;i++){
		st.insert({deg[i],i});
	}

	int ans = 0;
	for (int i = 0; i < n; ++i)
	{
		int first = deg[i];
		st.erase({deg[i],i});
		vpii store;
		for(auto child : adj[i]) {
			st.erase({deg[child],child});
			st.insert({deg[child] -1,child});
			store.pb({deg[child],child});
		}
		int second = (*prev(st.end())).ff;
		ans = max(ans,first + second -1);
		st.insert({deg[i],i});
		for(auto [count, val] : store) {
			st.erase({count-1,val});
			st.insert({count,val});
		}
	}
	cout<<ans<<endl;
}

int main() {

#ifndef ONLINE_JUDGE
	freopen("error.txt", "w", stderr);
#endif

	FASTIO();
	auto start1 = high_resolution_clock::now();
	int t = 1;
	cin >> t;
	int T = t;
	while (t--)
	{
	   #ifndef ONLINE_JUDGE
	   	cerr<<"Test "<<(T-t)<<" :"<<endl;
	   #endif
	   solve();
	   #ifndef ONLINE_JUDGE
	   	cerr<<"--------------------------"<<endl<<endl;
	   #endif
	}
	auto stop1 = high_resolution_clock::now();
	auto duration = duration_cast<microseconds>(stop1 - start1);
#ifndef ONLINE_JUDGE
	cerr << "Time elapsed : " << (duration . count() / 1000000) << '.' << (duration . count() % 1000000) << endl;
#endif

}

#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<typename T>
using orderedSet = tree<T , null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T>
using orderedMultiset = tree<T , null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k) -> iterator at k
// order_of_key(k) -> number of items that are strictly smaller than k

#define FASTIO() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD1 1000000007
#define MOD9 998244353
#define INF 1e9
#define INF1 1e18
#define endl "\n"
#define pb push_back
#define ppb pop_back
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define all(x) (x).begin(), (x).end()
#define lb lower_bound
#define ub upper_bound
#define fcout cout<<fixed<<setprecision(10)
#define YES  cout<<"YES"<<endl
#define NO cout<<"NO"<<endl

typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;

// ---------------------------------- DEFINES ---------------------------------------
typedef vector <int> vi;
typedef vector <ll> vll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <vector <int> > vvi;
typedef vector <pii> vpii;
typedef vector <pll> vpll;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T, vector<T>, greater<T>>;
// ----------------------------------------------------------------------------------

// ---------------------------------- OPERATOR OVERLOADING ---------------------------------------
template<typename T>
istream& operator>>(istream &istream, vector<T> &v) {for (auto &x : v)cin >> x; return istream;}
template<typename T>
ostream& operator<<(ostream &ostream, const vector<T> &v) { for (auto &x : v) cout << x << " "; return ostream; }
template<typename T1, typename T2>
istream& operator>>(istream &istream, pair<T1, T2> &p) { return (istream >> p.ff >> p.ss); }
template<typename T1, typename T2>
ostream& operator<<(ostream &ostream, const pair<T1, T2> &p) { return (ostream << p.ff << " " << p.ss); }
template<typename T1, typename T2>
istream& operator>>(istream &istream, vector<pair<T1, T2>> &v) {for (auto &x : v)cin >> x; return istream;}
template<typename T1, typename T2>
ostream& operator<<(ostream &ostream, const vector<pair<T1, T2>> &v) { for (auto &x : v) cout << x << endl; return ostream; }
template<typename T>
istream& operator>>(istream &istream, vector<vector<T>> &v) {for (auto &x : v)cin >> x; return istream;}
template<typename T>
ostream& operator<<(ostream &ostream, const vector<vector<T>> &v) { for (auto &x : v) cout << x << endl; return ostream; }
// ------------------------------------------------------------------------------------------------

// ------------------------------------------ DEBUG ------------------------------------------------
#ifndef ONLINE_JUDGE
#define debug(x...) cerr <<__func__<<":"<<__LINE__<<" [" << #x << "] = "; _print(x); cerr << endl;
#define HERE cerr <<__func__<<":"<<__LINE__<<" [ here ] "; cerr << endl;
#else
#define debug(x...)
#endif

void _print(ll t) {cerr << t;}
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(lld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(ull t) {cerr << t;}

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 << "]";}
template <class T> void _print(vector <vector <T> > v) {cerr << "{ "; for (vector<T> i : v) {cerr << "[ "; for (T j : i) {_print(j); cerr << " ";}; cerr << "] ";} cerr << "}";}
template <class T, class V> void _print(vector < pair <T , V> > vp) {cerr << "{ "; for (pair<T, V> i : vp) {cerr << "[ "; "{"; _print(i.ff); cerr << ","; _print(i.ss); cerr << " ] ";} cerr << "}";}
template <class T> void _print(stack <T> st) {cerr << "[ "; while (!st.empty()) {_print(st.top()); st.pop(); cerr << " ";} cerr << "]";}
template <class T> void _print(queue <T> q) {cerr << "[ "; while (!q.empty()) {_print(q.front()); q.pop(); cerr << " ";} cerr << "]";}
template <class T> void _print(deque <T> dq) {cerr << "[ "; while (!dq.empty()) {_print(dq.front()); dq.pop_front(); cerr << " ";} cerr << "]";}
template <class T> void _print(PQ <T> pq) {cerr << "[ "; while (!pq.empty()) {_print(pq.top()); pq.pop(); cerr << " ";} cerr << "]";}
template <class T> void _print(QP <T> pq) {cerr << "[ "; while (!pq.empty()) {_print(pq.top()); pq.pop(); cerr << " ";} cerr << "]";}
//---------------------------------------------------------------------------------------------------

void solve() {

	//solution starts from here
	int n;
	cin>>n;

	vvi adj(n);
	vi deg(n);

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

	set<pii> st;
	for(int i=0;i<n;i++){
		st.insert({deg[i],i});
	}

	set<pii> temp = st;
	int ans = 0;
	for (int i = 0; i < n; ++i)
	{
		st = temp;
		int first = deg[i];
		st.erase({deg[i],i});
		vpii store;
		for(auto child : adj[i]) {
			st.erase({deg[child],child});
			st.insert({deg[child] -1,child});
		}
		store.pb({deg[i], i});
		debug(st)
		int second = (*prev(st.end())).ff;
		ans = max(ans,first + second -1);
	}
	cout<<ans<<endl;
}

int main() {

#ifndef ONLINE_JUDGE
	freopen("error.txt", "w", stderr);
#endif

	FASTIO();
	auto start1 = high_resolution_clock::now();
	int t = 1;
	cin >> t;
	int T = t;
	while (t--)
	{
	   #ifndef ONLINE_JUDGE
	   	cerr<<"Test "<<(T-t)<<" :"<<endl;
	   #endif
	   solve();
	   #ifndef ONLINE_JUDGE
	   	cerr<<"--------------------------"<<endl<<endl;
	   #endif
	}
	auto stop1 = high_resolution_clock::now();
	auto duration = duration_cast<microseconds>(stop1 - start1);
#ifndef ONLINE_JUDGE
	cerr << "Time elapsed : " << (duration . count() / 1000000) << '.' << (duration . count() % 1000000) << endl;
#endif

}

Answer: 1


#include <iostream>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>

using namespace std;

typedef long long ll;

#define x first
#define y second
#define int long long

const int MAXN = 2e5 + 100;
vector<int> g[MAXN];

int power[MAXN];
int used[MAXN];

void solve() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        g[i].clear();
        power[i] = 0;
    }
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        u--;
        v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    set<pair<int, int>> s;
    for (int i = 0; i < n; i++) {
        power[i] = g[i].size();
        s.insert({power[i], i});
    }
    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int u : g[i]) {
            s.erase({-power[u], u});
            power[u]--;
            s.insert({-power[u], u});
        }
        s.erase({-power[i], i});
        ans = max(ans, power[i] + -(s.begin()->x) - 1);
        s.insert({power[i], i});
        for (int u : g[i]) {
            s.erase({-power[u], u});
            power[u]++;
            s.insert({-power[u], u});
        }
    }
    cout << ans << '\n';
}

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

#include <iostream>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>

using namespace std;

typedef long long ll;

#define x first
#define y second
#define int long long

const int MAXN = 2e5 + 100;
vector<int> g[MAXN];

int power[MAXN];
int used[MAXN];

void solve() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        g[i].clear();
        power[i] = 0;
    }
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        u--;
        v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    set<pair<int, int>> s;
    for (int i = 0; i < n; i++) {
        power[i] = g[i].size();
        s.insert({power[i], i});
    }
    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int u : g[i]) {
            s.erase({-power[u], u});
            power[u]--;
            s.insert({-power[u], u});
        }
        s.erase({-power[i], i});
        ans = max(ans, power[i] + -(s.begin()->x) - 1);
        s.insert({-power[i], i});
        for (int u : g[i]) {
            s.erase({-power[u], u});
            power[u]++;
            s.insert({-power[u], u});
        }
    }
    cout << ans << '\n';
}

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

Answer: 2


#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
typedef long long ll;
vector<set<int>> g;
vector<int> vis;
void dfs (int v) {
    vis[v] = 1;
    for (int u : g[v]) {
        if (!vis[u]) dfs(u);
    }
}
void solve() {
    int n; cin >> n;
    g = vector<set<int>> (n);
    for (int i = 1; i < n; i++) {
        int u, v; cin >> u >> v;
        g[--u].insert(--v), g[v].insert(u);
    }
    vector<pair<int,int>> cnt;
    for (int i = 0; i < n; i++) cnt.push_back({g[i].size(), i});
    sort(cnt.rbegin(), cnt.rend());
    int del = cnt.begin()->second;
    for (int x : g[del]) {
        g[x].erase(del);
    }
    g[del].clear();
    cnt.clear();
    for (int i = 0; i < n; i++) {
        if (i == del) continue;
        cnt.push_back({g[i].size(), i});
    }
    sort(cnt.rbegin(), cnt.rend());
    int del2 = cnt.begin()->second;
    for (int x : g[del2]) {
        g[x].erase(del2);
    }
    g[del2].clear();
    int ans = 0;
    vis = vector<int> (n);
    for (int i = 0; i < n; i++) {
        if (!vis[i] and i != del and i != del2) ans++, dfs(i);
    }
    cout << ans << '\n';
}
int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int t = 1; cin >> t;
    while (t--) solve();

}

#include <iostream>
#include <vector>
#include <set>
using namespace std;
typedef long long ll;
void solve() {
    int n; cin >> n;
    vector<set<int>> g(n);
    for (int i = 1; i < n; i++) {
        int u, v; cin >> u >> v;
        g[--u].insert(--v), g[v].insert(u);
    }
    multiset<int, greater<int>> s;
    for (auto x : g) s.insert(x.size());
    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int j : g[i]) ans = max(ans, (int)g[i].size() + (int)g[j].size() - 2);
    }
    for (int i = 0; i < n; i++) {
        s.erase(s.find(g[i].size()));
        for (int j : g[i]) s.erase(s.find(g[j].size()));
        if (s.size()) {
            ans = max(ans, (int)g[i].size() + *s.begin() - 1);
        }
        for (int j : g[i]) s.insert(g[j].size());
        s.insert(g[i].size());
    }
    cout << ans << '\n';
}
int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int t = 1; cin >> t;
    while (t--) solve();

}

Answer: 2


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

void solve() {
  int n;
  cin >> n;
  vector<vector<int>> graph(n + 1);
  vector<int> degree(n + 1, 0);
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    graph[u].push_back(v);
    graph[v].push_back(u);
    degree[u]++;
    degree[v]++;
  }
  for (int u = 1; u <= n; u++)
    sort(graph[u].begin(), graph[u].end());
  vector<pair<int, int>> L;
  L.reserve(n);
  for (int u = 1; u <= n; u++)
    L.push_back({degree[u], u});
  sort(L.rbegin(), L.rend());
  ll best_nonadj = -1;
  for (int u = 1; u <= n; u++) {
    ll candidate = -1;
    for (auto &p : L) {
      int v = p.second;
      if (v == u) continue;
      if (binary_search(graph[u].begin(), graph[u].end(), v)) continue;
      candidate = (ll)degree[u] + degree[v] - 1;
      break;
    }
    best_nonadj = max(best_nonadj, candidate);
  }
  ll best_adj = -1;
  for (int u = 1; u <= n; u++) {
    for (int v : graph[u])
      if (v > u)
        best_adj = max(best_adj, (ll)degree[u] + degree[v] - 2);
  }
  ll ans = max(best_nonadj, best_adj);
  cout << ans << '\n';
}

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

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

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

  vector<vector<int>> graph(n + 1);
  vector<int> degree(n + 1, 0);

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

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

  vector<pair<int, int>> candidates;
  for (int i = 1; i <= n; i++)
    candidates.push_back({degree[i], i});

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

  int k = min(n, 200);
  vector<pair<int, int>> topcans(candidates.begin(), candidates.begin() + k);

  vector<unordered_set<int>> neighbors(k);
  for (int i = 0; i < k; i++) {
    int v = topcans[i].second;
    for (int neighbor : graph[v])
      neighbors[i].insert(neighbor);
  }

  ll best = 0;
  for (int i = 0; i < k; i++) {
    for (int j = i + 1; j < k; j++) {
      int u = topcans[i].second;
      int v = topcans[j].second;

      bool adj = (neighbors[i].find(v) != neighbors[i].end());
      ll current = degree[u] + degree[v] - 1 - (adj ? 1 : 0);

      best = max(best, current);
    }
  }

  cout << best << '\n';
}

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

Answer: 1


//
// Created by Jiwon Sheen on 2025-02-02
//
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

inline void fastIo() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
}

using pii = pair<int, int>;

int main() {
    int t;
    int n;
    int ans;
    vector<vector<int>> v;
    vector<int> de, de2;
    vector<bool> chk;
    priority_queue<pii> pq;

    fastIo();

    cin >> t;

    while (t--) {
        cin >> n;

        ans = 1;
        v.assign(n + 1, vector<int>());
        de.assign(n + 1, 0);
        de2.assign(n + 1, 0);
        chk.assign(n + 1, false);

        for (int i = 0; i < n - 1; i++) {
            int a, b;
            cin >> a >> b;
            de[a]++, de[b]++;
            de2[a]++, de2[b]++;
            v[a].push_back(b);
            v[b].push_back(a);
        }

        for (int i = 1; i <= n; i++)
            pq.emplace(de[i], i);

        for (int k = 0; k < 2; k++) {
            while (pq.top().first != de[pq.top().second])
                pq.pop();
            auto [cd, idx] = pq.top();
            pq.pop();
            chk[idx] = true;

            ans += cd - 1;
            for (const auto &nxt: v[idx]) {
                if (!chk[nxt])
                    pq.emplace(--de[nxt], nxt);
            }
        }

        while (!pq.empty())
            pq.pop();

        if (n >= 3) {
            int ans2 = 1;

            for (int i = 1; i <= n; i++)
                pq.emplace(de2[i], i);

            chk.assign(n + 1, false);
            chk[pq.top().second] = true;
            pq.pop();

            for (int k = 0; k < 2; k++) {
                while (pq.top().first != de2[pq.top().second])
                    pq.pop();
                auto [cd, idx] = pq.top();
                pq.pop();
                chk[idx] = true;

                ans2 += cd - 1;
                for (const auto &nxt: v[idx]) {
                    if (!chk[nxt])
                        pq.emplace(--de2[nxt], nxt);
                }
            }
            ans = max(ans, ans2);

            while (!pq.empty())
                pq.pop();
        }

        cout << ans << '\n';
    }

    return 0;
}

//
// Created by Jiwon Sheen on 2025-02-02
//
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

inline void fastIo() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
}

using pii = pair<int, int>;

int main() {
    int t;
    int n;
    int ans;
    vector<vector<int>> v;
    vector<int> de, de2;
    vector<bool> chk;
    priority_queue<pii> pq;

    fastIo();

    cin >> t;

    while (t--) {
        cin >> n;

        ans = 1;
        v.assign(n + 1, vector<int>());
        de.assign(n + 1, 0);
        de2.assign(n + 1, 0);
        chk.assign(n + 1, false);

        for (int i = 0; i < n - 1; i++) {
            int a, b;
            cin >> a >> b;
            de[a]++, de[b]++;
            de2[a]++, de2[b]++;
            v[a].push_back(b);
            v[b].push_back(a);
        }

        for (int i = 1; i <= n; i++)
            pq.emplace(de[i], i);

        for (int k = 0; k < 2; k++) {
            while (pq.top().first != de[pq.top().second])
                pq.pop();
            auto [cd, idx] = pq.top();
            pq.pop();
            chk[idx] = true;

            ans += cd - 1;
            for (const auto &nxt: v[idx]) {
                if (!chk[nxt])
                    pq.emplace(--de[nxt], nxt);
            }
        }

        while (!pq.empty())
            pq.pop();

        if (n >= 3) {
            int ans2 = 1;

            for (int i = 1; i <= n; i++)
                pq.emplace(de2[i], i);

            chk.assign(n + 1, false);
            chk[pq.top().second] = true;
            pq.pop();

            for (int k = 0; k < 2; k++) {
                while (pq.top().first != de2[pq.top().second])
                    pq.pop();
                auto [cd, idx] = pq.top();
                pq.pop();
                chk[idx] = true;

                ans2 += cd - 1;
                for (const auto &nxt: v[idx]) {
                    if (!chk[nxt])
                        pq.emplace(--de2[nxt], nxt);
                }
            }
            ans = max(ans, ans2);
        }

        cout << ans << '\n';
    }

    return 0;
}

Answer: 1


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#define int long long
using namespace std;
int mod=998244353;
int INF=-1e10;
void dfs(int u,int p,auto &adj,auto &dp,auto &dgr){
    for(auto v:adj[u]){
        if(v==p) continue;
        dfs(v,u,adj,dp,dgr);
        dp[u][1][0]=max({dp[u][1][0],dp[v][1][1],dp[v][1][0]});
        dp[u][2][0]=max({dp[u][2][0],dp[v][2][0],dp[v][2][1]});
        dp[u][1][1]=dgr[u];
        dp[u][2][1]=max({dp[u][2][1],dp[v][1][1]+dgr[u]-2,dp[v][1][0]+dgr[u]-1});
    }
    if(dgr[u]==1 && u!=0){
        dp[u][1][0] = 0;
        dp[u][2][0] = 0;
        dp[u][1][1] = 1;
        dp[u][2][1] = 0;
    }
}
void solve(){
    int n;
    cin>>n;
    vector<vector<int>> adj(n);
    vector<vector<vector<int>>> dp(n,vector<vector<int>>(3,vector<int>(2,0)));
    vector<int> dgr(n,0);
    for(int i=0;i<n-1;i++){
        int u,v;
        cin>>u>>v;
        u--;v--;
        dgr[u]++;
        dgr[v]++;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    dfs(0,-1,adj,dp,dgr);
    //cout<<dp[4][1][1]<<endl;
    cout<<max(dp[0][2][0],dp[0][2][1])<<endl;
}
int32_t main(){
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
}

#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#define int long long
using namespace std;
int mod=998244353;
int INF=-1e10;
void dfs(int u,int p,auto &adj,auto &dp,auto &dgr){
    int m1=0;
    int m2=0;
    for(auto v:adj[u]){
        if(v==p) continue;
        dfs(v,u,adj,dp,dgr);
        if(m1<=max(dp[v][1][1],dp[v][1][0])){
            m2=m1;
            m1=max(dp[v][1][1],dp[v][1][0]);
        }
        else if(m2<max(dp[v][1][1],dp[v][1][0])){
            m2=max(dp[v][1][1],dp[v][1][0]);
        }
        dp[u][1][0]=max({dp[u][1][0],dp[v][1][1],dp[v][1][0]});
        dp[u][2][0]=max({dp[u][2][0],dp[v][2][0],dp[v][2][1]});
        dp[u][1][1]=dgr[u];
        dp[u][2][1]=max({dp[u][2][1],dp[v][1][1]+dgr[u]-2,dp[v][1][0]+dgr[u]-1});
    }
    dp[u][2][0]=max(dp[u][2][0],m1+m2-1);
    if(dgr[u]==1){
        dp[u][1][1] = 1;
    }
}
void solve(){
    int n;
    cin>>n;
    vector<vector<int>> adj(n);
    vector<vector<vector<int>>> dp(n,vector<vector<int>>(3,vector<int>(2,0)));
    vector<int> dgr(n,0);
    for(int i=0;i<n-1;i++){
        int u,v;
        cin>>u>>v;
        u--;v--;
        dgr[u]++;
        dgr[v]++;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    dfs(0,-1,adj,dp,dgr);
    cout<<max(dp[0][2][0],dp[0][2][1])<<endl;
}
int32_t main(){
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
}

Answer: 2


#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <queue>
#include <bits/stdc++.h>
#define ll long long
#define int long long
#define pb push_back
#define ppb pop_back
#define mp make_pair
using namespace std;
using vpi = vector<pair<int, int>>;
using pi = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
#define ff first
#define ss second
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
const int inf = 9e18;
const int mod = 1e9 + 7;
const int NUM = 1000030;
const int N = 10000000;
#define DEBUG(x) cerr << #x << ": " << x << '\n'
template <typename T, typename Y>
istream &operator>>(istream &is, pair<T, Y> &p)
{
    is >> p.first >> p.second;
    return is;
}
template <typename T, typename Y>
ostream &operator<<(ostream &os, pair<T, Y> p)
{
    os << p.first << ' ' << p.second << ' ';
    return os;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v)
{
    for (auto &i : v)
        is >> i;
    return is;
}
template <typename T>
ostream &operator<<(ostream &os, vector<T> v)
{
    for (auto &i : v)
        os << i << ' ';
    return os;
}
vector<int> lp, sieve;
vector<int> pr;
vector<int> power;
vector<int> fact;
void initpow(int x)
{
    power.resize(NUM);
    power[0] = 1;
    for (int i = 1; i < NUM; i++)
    {
        power[i] = (power[i - 1] * (x % mod)) % mod;
    }
}
void initFactorial()
{
    fact.resize(NUM);
    fact[0] = 1;
    for (int i = 1; i < NUM; i++)
    {
        fact[i] = (fact[i - 1] * i) % mod;
    }
}
void calc_sieve()
{
    sieve.resize(NUM + 1, 0);
    for (int x = 2; x <= NUM; x++)
    {
        if (sieve[x])
            continue;
        for (int u = x; u <= NUM; u += x)
        {
            sieve[u] = x;
        }
    }
}
void primefactor()
{
    lp.resize(N + 1, 0);
    for (int i = 2; i <= N; ++i)
    {
        if (lp[i] == 0)
        {
            lp[i] = i;
            pr.push_back(i);
        }
        for (int j = 0; j < (int)pr.size() && pr[j] <= lp[i] && i * pr[j] <= N; ++j)
            lp[i * pr[j]] = pr[j];
    }
}
int binpow(int a, int b)
{
    int res = 1;
    while (b > 0)
    {
        if (b & 1)
            res = res * a;
        a = a * a;
        b >>= 1;
    }
    return res;
}
int binpow(int a, int b, int mod)
{
    int res = 1;
    while (b > 0)
    {
        if (b & 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res % mod;
}
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}
int lcm(int a, int b)
{
    return ((a / gcd(a, b)) * b);
}
int inversemod(int a, int mod)
{
    return binpow(a, mod - 2, mod);
}
int divmod(int a, int b, int c)
{
    return ((a % c) * inversemod(b, c)) % c;
}
int combination(int n, int k)
{
    if (k > n)
        return 0;
    int p1 = (fact[n] * inversemod(fact[k], mod)) % mod;
    int p2 = (1 * inversemod(fact[n - k], mod)) % mod;
    return (p1 * p2) % mod;
}
void solve()
{
    int n;
    cin >> n;
    int deg[n];
    for (int i = 0; i < n; i++)
        deg[i] = 0;

    vector<vector<int>> adj(n);
    for (int i = 0; i < n - 1; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        deg[x]++;
        deg[y]++;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    int ans = 0;
    int maxver = -1;
    int freq = 0;
    for (int i = 0; i < n; i++)
    {
        if (freq < deg[i])
        {
            freq = deg[i];
            maxver = i;
        }
    }
    ans += freq;
    deg[maxver] = 0;

    for (auto it : adj[maxver])
    {
        deg[it]--;
    }
    freq = 0, maxver = -1;
    for (int i = 0; i < n; i++)
    {
        if (freq < deg[i])
        {
            freq = deg[i];
            maxver = i;
        }
    }
    ans += freq;
    cout << ans - 1 << "\n";
}
signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int t = 1;
    cin >> t;
    // ll a = 134, b = 132, c = 137;
    // cout << (a ^ b + b ^ c + c ^ a) << endl;
    while (t--)
        solve();
    return 0;
}

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <queue>
#include <bits/stdc++.h>
#define ll long long
#define int long long
#define pb push_back
#define ppb pop_back
#define mp make_pair
using namespace std;
using vpi = vector<pair<int, int>>;
using pi = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
#define ff first
#define ss second
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
const int inf = 9e18;
const int mod = 1e9 + 7;
const int NUM = 1000030;
const int N = 10000000;
#define DEBUG(x) cerr << #x << ": " << x << '\n'
template <typename T, typename Y>
istream &operator>>(istream &is, pair<T, Y> &p)
{
    is >> p.first >> p.second;
    return is;
}
template <typename T, typename Y>
ostream &operator<<(ostream &os, pair<T, Y> p)
{
    os << p.first << ' ' << p.second << ' ';
    return os;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v)
{
    for (auto &i : v)
        is >> i;
    return is;
}
template <typename T>
ostream &operator<<(ostream &os, vector<T> v)
{
    for (auto &i : v)
        os << i << ' ';
    return os;
}
vector<int> lp, sieve;
vector<int> pr;
vector<int> power;
vector<int> fact;
void initpow(int x)
{
    power.resize(NUM);
    power[0] = 1;
    for (int i = 1; i < NUM; i++)
    {
        power[i] = (power[i - 1] * (x % mod)) % mod;
    }
}
void initFactorial()
{
    fact.resize(NUM);
    fact[0] = 1;
    for (int i = 1; i < NUM; i++)
    {
        fact[i] = (fact[i - 1] * i) % mod;
    }
}
void calc_sieve()
{
    sieve.resize(NUM + 1, 0);
    for (int x = 2; x <= NUM; x++)
    {
        if (sieve[x])
            continue;
        for (int u = x; u <= NUM; u += x)
        {
            sieve[u] = x;
        }
    }
}
void primefactor()
{
    lp.resize(N + 1, 0);
    for (int i = 2; i <= N; ++i)
    {
        if (lp[i] == 0)
        {
            lp[i] = i;
            pr.push_back(i);
        }
        for (int j = 0; j < (int)pr.size() && pr[j] <= lp[i] && i * pr[j] <= N; ++j)
            lp[i * pr[j]] = pr[j];
    }
}
int binpow(int a, int b)
{
    int res = 1;
    while (b > 0)
    {
        if (b & 1)
            res = res * a;
        a = a * a;
        b >>= 1;
    }
    return res;
}
int binpow(int a, int b, int mod)
{
    int res = 1;
    while (b > 0)
    {
        if (b & 1)
            res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res % mod;
}
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}
int lcm(int a, int b)
{
    return ((a / gcd(a, b)) * b);
}
int inversemod(int a, int mod)
{
    return binpow(a, mod - 2, mod);
}
int divmod(int a, int b, int c)
{
    return ((a % c) * inversemod(b, c)) % c;
}
int combination(int n, int k)
{
    if (k > n)
        return 0;
    int p1 = (fact[n] * inversemod(fact[k], mod)) % mod;
    int p2 = (1 * inversemod(fact[n - k], mod)) % mod;
    return (p1 * p2) % mod;
}
void solve()
{
    int n;
    cin >> n;
    int deg[n];
    for (int i = 0; i < n; i++)
        deg[i] = 0;

    set<pair<int, int>> vp;
    for (int i = 0; i < n - 1; i++)
    {
        int x, y;
        cin >> x >> y;
        x--, y--;
        deg[x]++;
        deg[y]++;
        vp.insert({x, y});
        vp.insert({y, x});
    }
    int ans = 0;
    vector<pair<int, int>> temp;
    for (int i = 0; i < n; i++)
    {
        temp.push_back({-deg[i], i});
    }
    sort(temp.begin(), temp.end());

    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (vp.find({temp[i].second, temp[j].second}) == vp.end())
            {
                ans = max(ans, (-temp[i].first) + (-temp[j].first) - 1);
                break;
            }
        }
    }
    for (auto it : vp)
    {
        ans = max(ans, deg[it.first] + deg[it.second] - 2);
    }
    cout << ans << "\n";
}
signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int t = 1;
    cin >> t;
    // ll a = 134, b = 132, c = 137;
    // cout << (a ^ b + b ^ c + c ^ a) << endl;
    while (t--)
        solve();
    return 0;
}

Answer: 2


#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<set>
#include<string.h>
#include<cstdio>
#include<map>
#include<math.h>
#include<algorithm>
#include<queue>
#include<utility>
#include<unordered_map>
#include<bitset>
#include<iomanip>
using namespace std;
#define IOS ios::sync_with_stdio;cin.tie(0);
#define PII pair<int,int>
#define PLL pair<ll,ll>
#define ll long long
#define lf double
#define MAX_NUM 10000
void solve(){
	int n;
	cin>>n;
	map<int,int>du;
//	map<int,int>reserve_du;
	map<int,set<int>>child;
	for(int i=1;i<=n-1;i++){
		int a,b;
		cin>>a>>b;
		du[a]+=1;
		du[b]+=1;
		child[a].insert(b);
		child[b].insert(a);
	}

	vector<int>ans_arr;
	int max_du=-1;
	int cnt=5;
	for(auto x:du)max_du=max(max_du,x.second);
	for(auto x:du){
		if(x.second!=max_du)continue;
		int ord=x.first;
		for(int i=1;i<=n;i++){
			if(i==ord)continue;
			if(child[ord].find(i)!=child[ord].end()){
				ans_arr.push_back(du[ord]+du[i]-2);
			}else {
				ans_arr.push_back(du[ord]+du[i]-1);
			}
		}
		if(cnt--==0)break;
	}
	int ans=-1;
	for(auto x:ans_arr){
		ans=max(ans,x);
	}
	cout<<ans<<endl;
}
int main(){
	IOS;
	int T;
	cin>>T;
//	T=1;
	while(T--){
		solve();
	}
	return 0;
}

#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<set>
#include<string.h>
#include<cstdio>
#include<map>
#include<math.h>
#include<algorithm>
#include<queue>
#include<utility>
#include<unordered_map>
#include<bitset>
#include<iomanip>
using namespace std;
#define IOS ios::sync_with_stdio;cin.tie(0);
#define PII pair<int,int>
#define PLL pair<ll,ll>
#define ll long long
#define lf double
#define MAX_NUM 10000
void solve(){
	int n;
	cin>>n;
	map<int,int>du;
//	map<int,int>reserve_du;
	map<int,set<int>>child;
	for(int i=1;i<=n-1;i++){
		int a,b;
		cin>>a>>b;
		du[a]+=1;
		du[b]+=1;
		child[a].insert(b);
		child[b].insert(a);
	}

	vector<int>ans_arr;
	int max_du=-1;
	for(auto x:du)max_du=max(max_du,x.second);
	for(auto x:du){
		if(x.second!=max_du)continue;
		int ord=x.first;
		for(int i=1;i<=n;i++){
			if(i==ord)continue;
			if(child[ord].find(i)!=child[ord].end()){
				ans_arr.push_back(du[ord]+du[i]-2);
			}else {
				ans_arr.push_back(du[ord]+du[i]-1);
			}
		}
	}
	int ans=-1;
	for(auto x:ans_arr){
		ans=max(ans,x);
	}
	cout<<ans<<endl;
}
int main(){
	IOS;
	int T;
	cin>>T;
//	T=1;
	while(T--){
		solve();
	}
	return 0;
}

Answer: 1


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

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

using namespace std;

#define ll long long
#define endl '\n'
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define fr(i, j, n) for (int i = j; i < n; i++)
#define fastIO ios::sync_with_stdio(false), cin.tie(NULL);
#define ll1 (ll)1
#define ff first
#define ss second
#define YES cout << "YES\n"
#define NO cout << "NO\n"

#ifndef ONLINE_JUDGE
#include "template.cpp"
#else
#define debug(...)
#define debugArr(...)
#endif

typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ordered_set;
const int MOD = 1e9 + 7;

/*
unordered_map<ll, ll> mp1;
mp.reserve(1024);
mp.max_load_factor(0.25);
*/

template <typename T>
T _gcd(T __m, T __n)
{
    while (__n != 0)
    {
        T __t = __m % __n;
        __m = __n;
        __n = __t;
    }
    return __m;
}
template <typename T>
T Set(T N, T pos) { return N = N | (1 << pos); }
template <typename T>
T reset(T N, T pos) { return N = N & ~(1 << pos); }
template <typename T>
bool check(T N, T pos) { return (bool)(N & (1 << pos)); }

int32_t main()
{
    fastIO;
    int t = 1;
    cin >> t;
    while (t--)
    {
        ll n, u, v;
        cin >> n;
        set<pair<ll, ll>> st;
        vector<ll> degree(n + 1);
        vector<vector<ll>> adj(n + 1);
        for (int i = 1; i < n; i++)
        {
            cin >> u >> v;
            adj[u].push_back(v), adj[v].push_back(u);
            degree[u]++, degree[v]++;
        }
        for (int i = 1; i <= n; i++)
        {
            st.insert({degree[i], i});
        }
        set<ll> ans;
        for (int i = 1; i <= n; i++)
        {
            vector<pair<ll, ll>> nst;
            nst.push_back({degree[i], i});
            st.extract({degree[i], i});
            for (auto it : adj[i])
            {
                ans.insert(degree[i] + degree[it] - 2);
                nst.push_back({degree[it], it});
                st.extract({degree[it], it});
            }
            if (!st.empty())
            {
                auto it = *st.rbegin();
                ans.insert(degree[i] + it.ff - 1);
            }
            for (auto it : nst)
            {
                st.insert({it.ff, it.ss});
            }
        }
        cout << *ans.rbegin() << endl;
    }
    return 0;
}

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

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

using namespace std;

#define ll long long
#define endl '\n'
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define fr(i, j, n) for (int i = j; i < n; i++)
#define fastIO ios::sync_with_stdio(false), cin.tie(NULL);
#define ll1 (ll)1
#define ff first
#define ss second
#define YES cout << "YES\n"
#define NO cout << "NO\n"

#ifndef ONLINE_JUDGE
#include "template.cpp"
#else
#define debug(...)
#define debugArr(...)
#endif

typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ordered_set;
const int MOD = 1e9 + 7;

/*
unordered_map<ll, ll> mp1;
mp.reserve(1024);
mp.max_load_factor(0.25);
*/

template <typename T>
T _gcd(T __m, T __n)
{
    while (__n != 0)
    {
        T __t = __m % __n;
        __m = __n;
        __n = __t;
    }
    return __m;
}
template <typename T>
T Set(T N, T pos) { return N = N | (1 << pos); }
template <typename T>
T reset(T N, T pos) { return N = N & ~(1 << pos); }
template <typename T>
bool check(T N, T pos) { return (bool)(N & (1 << pos)); }

int32_t main()
{
    fastIO;
    int t = 1;
    cin >> t;
    while (t--)
    {
        ll n, u, v;
        cin >> n;
        vector<ll> degree(n + 1);
        vector<set<ll>> adj(n + 1);
        for (int i = 1; i < n; i++)
        {
            cin >> u >> v;
            adj[u].insert(v), adj[v].insert(u);
            degree[u]++, degree[v]++;
        }
        vector<pair<ll, ll>> ndeg;
        for (int i = 1; i <= n; i++)
        {
            ndeg.push_back({degree[i], i});
        }
        sort(rall(ndeg));
        ll secondMax = ndeg[1].ff, ans = ndeg[0].ff, root = ndeg[0].ss, i = 1;
        set<ll> val;
        while (i < ndeg.size())
        {
            if (adj[root].find(ndeg[i].ss) != adj[root].end())
            {
                val.insert(ans + ndeg[i].ff - 2);
            }
            else
            {
                val.insert(ans + ndeg[i].ff - 1);
            }
            i++;
        }
        assert(!val.empty());
        cout << *val.rbegin() << endl;
    }
    return 0;
}

Answer: 1


#include <stdio.h>
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N=1e5+200;
set<int>e[N];
vector<pair<int,int>>v;
int a[N];
bool cmp(pair<int,int>x,pair<int,int>y){
	return x.second>y.second;
}
int main(){
	int t;
	cin>>t;
	while(t--){
		ll n;
		cin>>n;
		v.clear();
		for(int i=1;i<=n;++i){
			a[i]=0;
			e[i].clear();
		}
		int mx=0;
		for(int i=1;i<n;++i){
			int x,y;
			cin>>x>>y;
			e[x].insert(y);
			e[y].insert(x);
			a[x]++;
			a[y]++;
		}
		for(int i=1;i<=n;++i) v.push_back({i,a[i]});
		sort(v.begin(),v.end(),cmp);
		int ans=1;
		int cnt=0;
		while(cnt<n-1&&v[cnt].second==v[cnt+1].second) cnt++;
		if(cnt==0){
			ans+=v[0].second-1;
			ans+=v[1].second-1;
			int f=1;
			cnt=1;
			while(cnt<n&&v[cnt].second==v[cnt+1].second) cnt++;
			for(int i=1;i<=cnt;++i){
				if(e[v[i].first].find(v[0].first)==e[v[i].first].end()){
					f=0;
					break;
				}
			}
			if(f) ans--;
		}else if(cnt==1){
			ans+=v[0].second-1;
			ans+=v[1].second-1;
			if(e[v[0].first].find(v[1].first)!=e[v[0].first].end())ans--;
		}else{
			ans+=v[0].second-1;
			ans+=v[1].second-1;
		}
		cout<<max(ans,0)<<'\n';
	}
	return 0;
}

#include <stdio.h>
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N=2e5+200;
set<int>e[N];
vector<pair<int,int>>v;
int a[N];
bool cmp(pair<int,int>x,pair<int,int>y){
	return x.second>y.second;
}
int main(){
	int t;
	cin>>t;
	while(t--){
		ll n;
		cin>>n;
		v.clear();
		for(int i=1;i<=n;++i){
			a[i]=0;
			e[i].clear();
		}
		int mx=0;
		for(int i=1;i<n;++i){
			int x,y;
			cin>>x>>y;
			e[x].insert(y);
			e[y].insert(x);
			a[x]++;
			a[y]++;
		}
		for(int i=1;i<=n;++i) v.push_back({i,a[i]});
		sort(v.begin(),v.end(),cmp);
		int ans=1;
		int cnt=0;
		while(cnt<n-1&&v[cnt].second==v[cnt+1].second) cnt++;
		if(cnt==0){
			ans+=v[0].second-1;
			ans+=v[1].second-1;
			int f=1;
			cnt=1;
			while(cnt<n-1&&v[cnt].second==v[cnt+1].second) cnt++;
			for(int i=1;i<=cnt;++i){
				if(e[v[i].first].find(v[0].first)==e[v[i].first].end()){
					f=0;
					break;
				}
			}
			if(f) ans--;
		}else if(cnt==1){
			ans+=v[0].second-1;
			ans+=v[1].second-1;
			if(e[v[0].first].find(v[1].first)!=e[v[0].first].end())ans--;
		}else{
			ans+=v[0].second-1;
			ans+=v[1].second-1;
		}
		cout<<max(ans,0)<<'\n';
	}
	return 0;
}

Answer: 2