#include<bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;
const int maxN = 1e6 + 5;
const int Mod = 1e9 + 7;
const int LG = 21;
int n,mx,mx1,d[maxN];
bool avail[maxN];
vector<int> adj[maxN];
void input()
{
    cin >> n;
    for (int i = 0;i <= n;++i)
    {
        adj[i].clear();
        d[i] = 0;
        avail[i] = true;
    }
    mx = 0;mx1 = 0;
    for (int i = 1;i < n;++i)
    {
        int u,v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
        if (adj[mx].size() < adj[u].size()) mx = u;
        if (adj[mx].size() < adj[v].size()) mx = v;
    }
    avail[mx] = false;
}
void dfs(int u)
{
    avail[u] = false;
    for (int v : adj[u])
    {
        if (!avail[v] || v == mx || v == mx1) continue;
        d[u]++;
        dfs(v);
    }
}
void solve()
{
    mx1 = 0;
    if (n <= 2) {cout << 0 << "\n";return;}
    for (int i = 1;i <= n;++i) if (avail[i]) dfs(i);
    if (mx == 1) mx1 = n;
    else mx1 = 1;
    for (int i = 1;i <= n;++i) if (d[mx1] < d[i]) mx1 = i;
    fill(avail + 1,avail + n + 1,true);
    int res = 0;
    //cerr << mx << " " << mx1 << "aa\n";
    avail[mx] = false;
    avail[mx1] = false;
    for (int i = 1;i <= n;++i)
    {
        if (avail[i])
        {
            dfs(i);
            ++res;
        }
    }
    cout << res << "\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
//    freopen("1.inp","r",stdin);
//    freopen("1.out","w",stdout);
    int t;
    cin >> t;
    while (t--)
    {
        input();
        solve();
    }
}

#include<bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;
const int maxN = 1e6 + 5;
const int Mod = 1e9 + 7;
const int LG = 21;
int n,mx,mx1,d[maxN];
bool avail[maxN];
vector<int> adj[maxN],p;
priority_queue<pair<int,int>> q;
void input()
{
    cin >> n;
    while (!q.empty()) q.pop();
    p.clear();
    mx = 0;
    for (int i = 0;i <= n;++i) adj[i].clear();
    for (int i = 1;i < n;++i)
    {
        int u,v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
        if (adj[mx].size() < adj[u].size()) mx = u;
        if (adj[mx].size() < adj[v].size()) mx = v;
    }
    for (int i = 1;i <= n;++i)
    {
        if (adj[i].size() == adj[mx].size()) p.push_back(i);
        d[i] = adj[i].size();
        q.push({d[i],i});
    }
}
void solve()
{
    if (n <= 2) {cout << 0 << "\n";return;}
    int res = -1e9;
    for (int u : p)
    {
        bool flag = false;
        for (int v : adj[u])
        {
            q.push({d[v] - 1,v});
            --d[v];
        }
        while (!q.empty() && (q.top().first != d[q.top().second] || q.top().second == u))
        {
            if (q.top().second == u) flag = true;
            q.pop();
        }
        //cerr << q.size() << " " << u << " " << q.top().second << "\n";
        res = max(res,d[u] + q.top().first - 1);
        for (int v : adj[u])
        {
            q.push({d[v] + 1,v});
            ++d[v];
        }
        if (flag) q.push({d[u],u});
    }
    cout << res << "\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
//    freopen("1.inp","r",stdin);
//    freopen("1.out","w",stdout);
    int t;
    cin >> t;
    while (t--)
    {
        input();
        solve();
    }
}

Answer: 2


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

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

    while(t--){

       int n ; cin>>n ;
       vector<int>indegree(n+1,0);
       vector<pair<int,int>>edges;
       map<int,set<int>>mp;
       for(int i =1  ; i<= (n-1) ; i++){
           int u,v ;
           cin>>u>>v;
           edges.push_back({u,v});
           indegree[u]++;
           indegree[v]++;
           mp[u].insert(v);
           mp[v].insert(u);
       }

       int ans = 0 ;
       for(int i = 0 ;  i<edges.size() ; i++){
           ans = max(ans,indegree[edges[i].first] + indegree[edges[i].second] - 2) ;
       }

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

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

       for(int i = 0 ; i<vec.size(); i++){
           for(int j = i+1 ; j< vec.size() ; j++){
               int u = vec[i].second ;
               int v = vec[j].second ;
               if(mp[u].find(v) == mp[u].end()){
                   ans = max(ans,indegree[v]+indegree[u]-1);
                   break;
               }

           }
       }

       cout<<ans<<endl;

    }
}

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

void dfs(int node, int pp , vector<int>&vis, vector<int>graph[]){

    vis[node] = 1;
    for(auto ch : graph[node]){
        if(ch == pp)continue ;
        if(!vis[ch]){
            dfs(ch,node,vis,graph);
        }
    }
}

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

    while(t--){

       int n ; cin>>n ;

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

       priority_queue<int>pq;
       for(int i = 1 ; i <= (n-1); i++){
           int u,v ;
           cin>>u>>v;
           indegree[u]++;
           indegree[v]++;
       }

       for(int i =1 ; i<=n ; i++){
           pq.push(indegree[i]);
       }

       if(n == 2){
           cout<<0<<endl;
       }
       else{
           int a = pq.top();pq.pop();
           int b = pq.top();pq.pop();
        //   cout<<a<<" "<<b<<endl;
           int ans = a+b-1 ;
           if(b == 1){
               ans--;
           }
           cout<<ans<<endl;
       }

    }
}

Answer: 1


//JAI SHREE RAM
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2")
typedef long long ll;
#define inf 1e18

/*
-----------------------------ordered set--------------------
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less
#include <iostream>
using namespace __gnu_pbds;
using namespace std;

typedef tree<int, null_type, less<int>, rb_tree_tag,
            tree_order_statistics_node_update>
    ordered_set;
*/

/*-----------------PRIME FACTOR-------------
for (int i = 2; i*i <= n; i = i+2)
{
    // While i divides n, print i and divide n
    while (n%i == 0)
    {
        printf("%d ", i);
        n = n/i;
    }
}
*/

/*-----------------------sieve----------------
vector<bool> prime(MAXN, false);
vector<bool> used(MAXN, false);
void precalc() {
    for (int i = 2; i < MAXN; ++i) {
        if (!used[i]) {
            prime[i] = true;
            for (int j = i; j < MAXN; j += i) {
                used[j] = true;
            }
        }
    }
}
*/

/*--------------------------------sqrt function------------------------
ll my_sqrt(ll a)
{
    ll l=0,r=5000000001;
    while(r-l>1)
    {
        ll mid=(l+r)/2;
        if(1ll*mid*mid<=a)l=mid;
        else r=mid;
    }
    return l;
}

ll getclosest(ll x)
{
    ll n = sqrt(x);
    if(n*n==x)
    {
        return 0;
    }
    else
    {
        return (n+1)*(n+1) - x;
    }
}
ll cur = 0;
    for(ll i=1;i<n;i++)
    {
        ll a,x;
        cin>>a>>x;
        cur+=x;
        cout<<cur+w*(n-i)-cur*(n-i-1)<<" ";
    }
    cout<<endl;

const int MAXN = 1e5+5;
vector<vector<int>>divisors(MAXN);
void precomp()
{
    for(int i=2;i<MAXN;i++)
    {
        for(int j = i;j<MAXN;j+=i)
        {
            divisors[j].push_back(i);
        }
    }
}
*/#include <bits/stdc++.h>
using namespace std;

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

    vector<vector<int>> graph(n + 1);
    vector<int> degree(n + 1);
    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]++;
    }
    multiset<int> work;
    for (int i = 1; i <= n; i++)
    {
        work.insert(degree[i]);
    }
    int comp = 0;
    for (int i = 1; i <= n; i++)
    {
        vector<int>in,rem;
        int cur = 0;
        work.erase(work.find(degree[i]));
        in.push_back(degree[i]);
        cur += degree[i];
        for (auto v : graph[i]) {
            work.erase(work.find(degree[v]));
            work.insert(degree[v] - 1);
            rem.push_back(degree[v]-1);
            in.push_back(degree[v]);
        }
        if (!work.empty())
        {
            cur += (*work.rbegin())-1;
        }
        for(auto p:in)
        {
            work.insert(p);
        }
        for(auto p:rem)
        {
            work.erase(work.find(p));
        }
        comp = max(comp, cur);
    }

    cout << comp << endl;
}

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

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

    return 0;
}

//JAI SHREE RAM
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2")
typedef long long ll;
#define inf 1e18

/*
-----------------------------ordered set--------------------
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less
#include <iostream>
using namespace __gnu_pbds;
using namespace std;

typedef tree<int, null_type, less<int>, rb_tree_tag,
            tree_order_statistics_node_update>
    ordered_set;
*/

/*-----------------PRIME FACTOR-------------
for (int i = 2; i*i <= n; i = i+2)
{
    // While i divides n, print i and divide n
    while (n%i == 0)
    {
        printf("%d ", i);
        n = n/i;
    }
}
*/

/*-----------------------sieve----------------
vector<bool> prime(MAXN, false);
vector<bool> used(MAXN, false);
void precalc() {
    for (int i = 2; i < MAXN; ++i) {
        if (!used[i]) {
            prime[i] = true;
            for (int j = i; j < MAXN; j += i) {
                used[j] = true;
            }
        }
    }
}
*/

/*--------------------------------sqrt function------------------------
ll my_sqrt(ll a)
{
    ll l=0,r=5000000001;
    while(r-l>1)
    {
        ll mid=(l+r)/2;
        if(1ll*mid*mid<=a)l=mid;
        else r=mid;
    }
    return l;
}

ll getclosest(ll x)
{
    ll n = sqrt(x);
    if(n*n==x)
    {
        return 0;
    }
    else
    {
        return (n+1)*(n+1) - x;
    }
}
ll cur = 0;
    for(ll i=1;i<n;i++)
    {
        ll a,x;
        cin>>a>>x;
        cur+=x;
        cout<<cur+w*(n-i)-cur*(n-i-1)<<" ";
    }
    cout<<endl;

const int MAXN = 1e5+5;
vector<vector<int>>divisors(MAXN);
void precomp()
{
    for(int i=2;i<MAXN;i++)
    {
        for(int j = i;j<MAXN;j+=i)
        {
            divisors[j].push_back(i);
        }
    }
}
*/
void solve()
{
    int n;cin>>n;
    vector<vector<int>>val(n+1);
    for(int i=0;i<n-1;i++)
    {
        int u,v;cin>>u>>v;
        val[u].push_back(v);
        val[v].push_back(u);
    }
    /*
    for(int i=1;i<=n;i++)
    {
        cout<<i<<" "<<val[i].size()<<" == ";
        for(int j = 0;j<val[i].size();j++)
        {
            cout<<val[i][j]<<" ";
        }
        cout<<endl;
    }
    */
    vector<pair<int,int>>degree,degree2;
    for(int i=1;i<=n;i++)
    {
        degree.push_back({val[i].size(),i});
    }
    sort(degree.begin(),degree.end());
    int comp = 0;
    if(degree.back().first==0)
    {
        if(degree.size()==1)
        {
            cout<<0<<endl;
            return;
        }
        else
        {
            comp--;
        }
    }
    else
    {
        if(degree.back().first!=1)
        {
            comp+=degree.back().first;
        }
        int del = degree.back().second;
        //cout<<"del: "<<del<<endl;
        set<int>cur;
        for(auto p:val[del])
        {
            cur.insert(p);
        }
        for(int i=0;i<n;i++)
        {
            if(degree[i].second==del)continue;
            else if(cur.count(degree[i].second))
            {
                degree2.push_back({degree[i].first-1,degree[i].second});
            }
            else
            {
                degree2.push_back({degree[i].first,degree[i].second});
            }
        }
    }
    sort(degree2.begin(),degree2.end());
    /*
    for(auto p:degree2)
    {
        cout<<p.first<<" "<<p.second<<endl;
    }
    */
    if(degree2.back().first==0)
    {
        if(degree2.size()==1)
        {
            cout<<0<<endl;
            return;
        }
        else
        {
            comp--;
        }
    }
    else
    {
        if(degree2.back().first!=1)
            comp+=degree2.back().first-1;
    }
    cout<<comp<<endl;

}

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

    int t;  // Fix type of t
    cin >> t;
    while (t--) {
        solve();
    }

    return 0;
}

Answer: 1


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

void solve(int n) {
    vector<vector<int>> adj(n+1);
    vector<int> deg(n+1, 0);
    for (int i = 0; i < n-1; i++) {
        int a, b;
        cin >> a >> b;
        adj[a].push_back(b);
        adj[b].push_back(a);
        deg[a]++; deg[b]++;
    }
    int mx1 = 0;
    for (int i = 1; i <= n; i++) if (deg[i] > deg[mx1]) mx1 = i;
    int ans = deg[mx1];
    deg[mx1] = 0;
    for (int u : adj[mx1]) deg[u]--;
    int mx2 = 0;
    for (int i = 1; i <= n; i++) if (deg[i] > deg[mx2]) mx2 = i;
    ans += deg[mx2] - 1;
    cout << ans << '\n';
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

    int tt;
    cin >> tt;
    while (tt--) {
        int n;
        cin >> n;
        solve(n);
    }

    return 0;
}

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

void solve(int n) {
    vector<vector<int>> adj(n+1);
    vector<int> deg(n+1, 0);
    for (int i = 0; i < n-1; i++) {
        int a, b;
        cin >> a >> b;
        adj[a].push_back(b);
        adj[b].push_back(a);
        deg[a]++; deg[b]++;
    }

    int c1 = 0, c2 = 0;
    for (int i = 1; i <= n; i++) {
        if (deg[i] >= deg[c2]) {
            c2 = i;
            if (deg[c2] >= deg[c1]) swap(c1, c2);
        }
    }

    int ans1 = 0, ans2 = 0;
    for (int u : adj[c1]) deg[u]--;
    for (int i = 1; i <= n; i++) if (i != c1) ans1 = max(ans1, deg[i]);
    for (int u : adj[c1]) deg[u]++;
    ans1 += (deg[c1]-1);
    for (int u : adj[c2]) deg[u]--;
    for (int i = 1; i <= n; i++) if (i != c2) ans2 = max(ans2, deg[i]);
    ans2 += (deg[c2]-1);
    cout << max(ans1, ans2) << '\n';
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

    int tt;
    cin >> tt;
    while (tt--) {
        int n;
        cin >> n;
        solve(n);
    }

    return 0;
}

Answer: 2


#include <bits/stdc++.h>

using namespace std;
//#define endl "\n"
#define speeed ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0);
#define ld long double

#define ll long long
#define sz(s) (int)size(s)
//#define int ll

void File() {
#ifndef ONLINE_JUDGE

    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    freopen("error.txt", "w", stderr);
#endif
}

ll tc = 1;
#define OO LLONG_MAX
#define ONBit(n, k) (n|(1ll<<k))
#define OFFBit(n, k) (n&(~(1ll<<k)))
#define IsON(n, k) ((n>>k)&1ll)
#define twopower(n) (1ll<<n)
ll MOD1 = 1e9 + 7;

bool valid(long long i, long long j, long long n, long long m) { return i >= 0 && i < n && j >= 0 && j < m; }

long long mul(long long x, long long y, const long long MOD = MOD1) { return ((x % MOD) * (y % MOD)) % MOD; }

long long add_MOD(long long x, long long y, long long MOD = MOD1) {
    return (((x % MOD) + (y % MOD)) % MOD + MOD) % MOD;
}

long long sub(long long a, long long b, long long m = MOD1) {
    return ((a % m) - (b % m) + m) % m;
}

ll SafeMul(ll a, ll b, ll m) {
    if (b == 0)return 0;
    ll res = SafeMul(a, b / 2, m);
    res = add_MOD(res, res, m);
    if (b & 1)return add_MOD(res, a, m);
    else return res;
}

ll fast_power(ll a, ll b, ll m) {
    if (b == 0)return 1;
    ll res = fast_power(a, b / 2, m);
    res = (res * res) % m;
    if (b & 1)return (res * a) % m;
    else return res;
}

/*ll fast_power(ll x, ll n, ll m) {
    ll result = 1;
    while (n > 0) {
        if (n % 2 == 1) {
            result = SafeMul(result, x, m);
        }
        x = SafeMul(x, x, m);
        n = n / 2;
    }
    return result;
}*/

int log2_floor(long long i) { return i ? __builtin_clzll(1) - __builtin_clzll(i) : 0; }

int power_of_2(int n) { return __builtin_popcountll(n) == 1; }

bool line_checking(int a1, int b1, int a2, int b2, int a3, int b3) {
    return (b2 - b1) * (a2 - a3) == (b2 - b3) * (a2 - a1);
}

pair<int, int> rotate(int i, int j, int n) { return make_pair(j, n - 1 - i); }

int comp_double(double a, double b, double error = 1e-7) {
    if (fabs(a - b) <= error)return 0;
    if (a < b)return 1;
    return -1;
}

int round(int x, int y) {
    if (y < 0)x *= -1, y *= -1;
    if (x < 0) {
        return (2 * x - y + 1) / (2 * y);
    }
    return (2 * x + y - 1) / (2 * y);
}

int floor(int x, int y) {
    return x / y;
}

int ceil(int x, int y) {
    return (x + y - 1) / y;
}

/*int round(int m,int x){return round(m/x)*x;}*/

int dx[]{0, 0, 1, -1, -1, -1, 1, 1};
int dy[]{1, -1, 0, 0, 1, -1, -1, 1};

ll egcd(ll a, ll b, ll &x, ll &y) { /// ax + by = gcd(a,b)
    if (!b) {
        x = 1;
        y = 0;
        return a;
    }
    ll g = egcd(b, a % b, y, x);
    y -= (a / b) * x;
    return g;
}

ll modInverse(ll a, ll m) { /// (a/b)%m = ((a%m)*(modInverse(b)%m))%m
    ll x, y, g;
    g = egcd(a, m, x, y);
    if (g > 1)
        return -1;
    return (x + m) % m;
}

void print(vector<int> &v) {
    for (auto item: v) {
        cout << item << " ";
    }
    cout << endl;
}

struct pair_hash {
    template<class T1, class T2>
    std::size_t operator()(const std::pair<T1, T2> &p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;
    }
};

int F(vector<set<int>> &adj, vector<bool> &vis) {
    int mx = 0, node = 1;
    for (int i = 1; i < adj.size(); ++i) {
        if (mx <= adj[i].size() and !vis[i]) {
            mx = adj[i].size();
            node = i;
        }
    }
    return node;
}

void dfs(int node, vector<bool> &vis, vector<set<int>> &adj) {
    vis[node] = true;
    for (auto child: adj[node]) {
        if (!vis[child]) {
            dfs(child, vis, adj);
        }
    }
}

void main_() {
    int n;
    cin >> n;
    vector<set<int>> adj(n + 1);
    for (int u, v, i = 0; i < n - 1; ++i) {
        cin >> u >> v;
        adj[u].insert(v);
        adj[v].insert(u);
    }
    int ans = 0;
    for (int node = 1; node <= n; ++node) {
        int curr = 0;
        for (auto child: adj[node]) {
            curr = max<int>(adj[child].size(), curr);
        }
        ans = max<int>(ans, curr + adj[node].size() - 2);
    }
    vector<bool> vis(n + 1, false);
    int node = F(adj, vis);
    for (auto child: adj[node]) {
        adj[child].erase(node);
    }
    adj[node].clear();
    vis[node] = 1;
    node = F(adj, vis);
    for (auto child: adj[node]) {
        adj[child].erase(node);
    }
    adj[node].clear();
    vis[node] = 1;
    int curr = 0;
    for (int i = 1; i <= n; ++i) {
        if (!vis[i]) {
            ++curr;
            dfs(i, vis, adj);
        }
    }
    ans= max(ans,curr);
    cout << ans;
}

void preprocessing() {

}

signed main() {
    speeed
    File();
//    freopen("business.in", "r", stdin);
    int t = 1;
    preprocessing();
    cin >> t;
    for (int i = 1; i <= t; ++i) {
//        cout << "Case #"<<i<<": " ;
        main_();
        ++tc;
        if (i != t)
            cout << endl;
    }
    return 0;
}

#include <bits/stdc++.h>

using namespace std;
//#define endl "\n"
#define speeed ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0);
#define ld long double

#define ll long long
#define sz(s) (int)size(s)
//#define int ll

void File() {
#ifndef ONLINE_JUDGE

    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    freopen("error.txt", "w", stderr);
#endif
}

ll tc = 1;
#define OO LLONG_MAX
#define ONBit(n, k) (n|(1ll<<k))
#define OFFBit(n, k) (n&(~(1ll<<k)))
#define IsON(n, k) ((n>>k)&1ll)
#define twopower(n) (1ll<<n)
ll MOD1 = 1e9 + 7;

bool valid(long long i, long long j, long long n, long long m) { return i >= 0 && i < n && j >= 0 && j < m; }

long long mul(long long x, long long y, const long long MOD = MOD1) { return ((x % MOD) * (y % MOD)) % MOD; }

long long add_MOD(long long x, long long y, long long MOD = MOD1) {
    return (((x % MOD) + (y % MOD)) % MOD + MOD) % MOD;
}

long long sub(long long a, long long b, long long m = MOD1) {
    return ((a % m) - (b % m) + m) % m;
}

ll SafeMul(ll a, ll b, ll m) {
    if (b == 0)return 0;
    ll res = SafeMul(a, b / 2, m);
    res = add_MOD(res, res, m);
    if (b & 1)return add_MOD(res, a, m);
    else return res;
}

ll fast_power(ll a, ll b, ll m) {
    if (b == 0)return 1;
    ll res = fast_power(a, b / 2, m);
    res = (res * res) % m;
    if (b & 1)return (res * a) % m;
    else return res;
}

/*ll fast_power(ll x, ll n, ll m) {
    ll result = 1;
    while (n > 0) {
        if (n % 2 == 1) {
            result = SafeMul(result, x, m);
        }
        x = SafeMul(x, x, m);
        n = n / 2;
    }
    return result;
}*/

int log2_floor(long long i) { return i ? __builtin_clzll(1) - __builtin_clzll(i) : 0; }

int power_of_2(int n) { return __builtin_popcountll(n) == 1; }

bool line_checking(int a1, int b1, int a2, int b2, int a3, int b3) {
    return (b2 - b1) * (a2 - a3) == (b2 - b3) * (a2 - a1);
}

pair<int, int> rotate(int i, int j, int n) { return make_pair(j, n - 1 - i); }

int comp_double(double a, double b, double error = 1e-7) {
    if (fabs(a - b) <= error)return 0;
    if (a < b)return 1;
    return -1;
}

int round(int x, int y) {
    if (y < 0)x *= -1, y *= -1;
    if (x < 0) {
        return (2 * x - y + 1) / (2 * y);
    }
    return (2 * x + y - 1) / (2 * y);
}

int floor(int x, int y) {
    return x / y;
}

int ceil(int x, int y) {
    return (x + y - 1) / y;
}

/*int round(int m,int x){return round(m/x)*x;}*/

int dx[]{0, 0, 1, -1, -1, -1, 1, 1};
int dy[]{1, -1, 0, 0, 1, -1, -1, 1};

ll egcd(ll a, ll b, ll &x, ll &y) { /// ax + by = gcd(a,b)
    if (!b) {
        x = 1;
        y = 0;
        return a;
    }
    ll g = egcd(b, a % b, y, x);
    y -= (a / b) * x;
    return g;
}

ll modInverse(ll a, ll m) { /// (a/b)%m = ((a%m)*(modInverse(b)%m))%m
    ll x, y, g;
    g = egcd(a, m, x, y);
    if (g > 1)
        return -1;
    return (x + m) % m;
}

void print(vector<int> &v) {
    for (auto item: v) {
        cout << item << " ";
    }
    cout << endl;
}

struct pair_hash {
    template<class T1, class T2>
    std::size_t operator()(const std::pair<T1, T2> &p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;
    }
};

void main_() {
    int n;
    cin >> n;
    vector<set<int>> adj(n + 1);
    vector<int>deg(n+1);
    multiset<pair<int,int>,greater<>>multiset1;
    for (int u, v, i = 0; i < n - 1; ++i) {
        cin >> u >> v;
        adj[u].insert(v);
        adj[v].insert(u);
        deg[u]++;
        deg[v]++;
    }

    for (int i = 1; i <= n ; ++i) {
        multiset1.insert({deg[i],i});
    }

    int ans = 0;
    for (int node = 1; node <= n ; ++node) {
        multiset1.erase({deg[node], node});
        for (auto child:adj[node]) {
            ans = max(ans, deg[node] + deg[child] - 2);
            multiset1.erase({deg[child],child});
        }

        int mx = multiset1.begin()->first;
        ans = max(ans, mx + deg[node] - 1);

        for (auto child:adj[node]) {
            ans = max(ans, deg[node] + deg[child] - 2);
            multiset1.insert({deg[child],child});
        }

        multiset1.insert({deg[node], node});
    }

    cout<<ans;

}

void preprocessing() {

}

signed main() {
    speeed
    File();
//    freopen("business.in", "r", stdin);
    int t = 1;
    preprocessing();
    cin >> t;
    for (int i = 1; i <= t; ++i) {
//        cout << "Case #"<<i<<": " ;
        main_();
        ++tc;
        if (i != t)
            cout << endl;
    }
    return 0;
}

Answer: 2


#include <iostream>
//#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <random>
#include <iterator>
#include <numeric>
#include <unordered_map>
#include <map>
#include <unordered_set>
#include <set>
#include <bitset>
//#include <limits>
#include <climits>
#include <queue>
#include <stack>
#include <deque>
#include <tuple>
#include <list>
#include <math.h>
#include <random>
#include <algorithm>
#include <chrono>
#include <iomanip>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
#include <array>
#include <tuple>
#include <functional>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <float.h>

/*
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ordered_set;

ordered_set st;
*/

// g++-13 -std=c++11 codeforce.cpp -o codeforce
// g++ -std=c++11 codeforce.cpp -o codeforce
// ./codeforce <codef.txt

using namespace std;
//using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
//typedef string str;

vector<int> manacher_odd(string s) {
    int n = s.size();
    s = "$" + s + "^";
    vector<int> p(n + 2);
    int l = 1, r = 1;
    for(int i = 1; i <= n; i++) {
        p[i] = max(0, min(r - i, p[l + (r - i)]));
        while(s[i - p[i]] == s[i + p[i]]) {
            p[i]++;
        }
        if(i + p[i] > r) {
            l = i - p[i], r = i + p[i];
        }
    }
    return vector<int>(begin(p) + 1, end(p) - 1);
}
vector<int> manacher(string s) {
    string t;
    for(auto c: s) {
        t += string("#") + c;
    }
    auto res = manacher_odd(t + "#");
    return vector<int>(begin(res) + 1, end(res) - 1);
}

// mt19937_64 rnd(98275314);
// ll gen(){
//     ll x=0;
//     while(x==0){
//         x=rnd();
//     }
//     return x;
// }
vector<int> z_function(string s) {
    int n = s.size();
    vector<int> z(n);
    int l = 0, r = 0;
    for(int i = 1; i < n; i++) {
        if(i < r) {
            z[i] = min(r - i, z[i - l]);
        }
        while(i + z[i] < n && s[z[i]] == s[i + z[i]]) {
            z[i]++;
        }
        if(i + z[i] > r) {
            l = i;
            r = i + z[i];
        }
    }
    return z;
}
/*
template<class T>
struct MaxFlow {
    struct _Edge {
        int to;
        T cap;
        _Edge(int to, T cap) : to(to), cap(cap) {}
    };
    int n;
    std::vector<_Edge> e;
    std::vector<std::vector<int> > g;
    std::vector<int> cur, h;
    MaxFlow() {}
    MaxFlow(int n) {
        init(n);
    }
    void init(int n) {
        this->n = n;
        e.clear();
        g.assign(n, {});
        cur.resize(n);
        h.resize(n);
    }
    bool bfs(int s, int t) {
        h.assign(n, -1);
        std::queue<int> que;
        h[s] = 0;
        que.push(s);
        while (!que.empty()) {
            const int u = que.front();
            que.pop();
            for (int i : g[u]) {
                auto [v, c] = e[i];
                if (c > 0 && h[v] == -1) {
                    h[v] = h[u] + 1;
                    if (v == t) {
                        return true;
                    }
                    que.push(v);
                }
            }
        }
        return false;
    }
    T dfs(int u, int t, T f) {
        if (u == t) {
            return f;
        }
        auto r = f;
        for (int &i = cur[u]; i < int(g[u].size()); ++i) {
            const int j = g[u][i];
            auto [v, c] = e[j];
            if (c > 0 && h[v] == h[u] + 1) {
                auto a = dfs(v, t, std::min(r, c));
                e[j].cap -= a;
                e[j ^ 1].cap += a;
                r -= a;
                if (r == 0) {
                    return f;
                }
            }
        }
        return f - r;
    }
    void addEdge(int u, int v, T c) {
        g[u].push_back(e.size());
        e.emplace_back(v, c);
        g[v].push_back(e.size());
        e.emplace_back(u, 0);
    }
    T flow(int s, int t) {
        T ans = 0;
        while (bfs(s, t)) {
            cur.assign(n, 0);
            ans += dfs(s, t, std::numeric_limits<T>::max());
        }
        return ans;
    }
    std::vector<bool> minCut() {
        std::vector<bool> c(n);
        for (int i = 0; i < n; i++) {
            c[i] = (h[i] != -1);
        }
        return c;
    }
    struct Edge {
        int from;
        int to;
        T cap;
        T flow;
    };
    std::vector<Edge> edges() {
        std::vector<Edge> a;
        for (int i = 0; i < e.size(); i += 2) {
            Edge x;
            x.from = e[i + 1].to;
            x.to = e[i].to;
            x.cap = e[i].cap + e[i + 1].cap;
            x.flow = e[i + 1].cap;
            a.push_back(x);
        }
        return a;
    }
};
*/
// std::mt19937_64 rng {std::chrono::steady_clock::now().time_since_epoch().count()};
const int N=2e5;
vector<int>G[N];
void solve(){
    int n;
    cin>>n;
    vector<int>deg(n);
    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);
        deg[u]++;
        deg[v]++;
    }
    vector<int>idx(n);
    int mx=*max_element(deg.begin(),deg.end());
    iota(idx.begin(),idx.end(),0);
    sort(idx.begin(),idx.end(), [&](int a, int b){
        return deg[a]>deg[b];
    });
    int ans=0;
    for(int j=0;j<min(3,n);++j){
        for(int i=0;i<n;++i){
            if(i==idx[j]){
                continue;
            }
            int adj=0;
            for(int it:G[i]){
                if(it==idx[j]){
                    adj=1;
                    break;
                }
            }
            ans=max(deg[idx[j]]+deg[i]-1-adj,ans);
        }
    }
    cout<<ans<<endl;
    for(int i=0;i<n;++i){
        G[i].clear();
    }
}
int main(int argc, char *argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cout<<std::setprecision(20);
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
}

/*

FOR ICPC style rounds, read all problems! don't get stuck on 1.
*/
/*prvb
nice trick:
up is down?

Fenwick
int lowbit(int i) { // gets the lowest set bit
	return (-i)&i;
}
adds 1 from [1,i];
void bitadd(int i) {
	for(;i<=n;i+=lowbit(i)) bit[i]++;
}
queries [1,i];
int bitqu(int i) {
	int ans=0;
	for(;i;i-=lowbit(i)) ans+=bit[i];
	return ans;
}
*/

#include <iostream>
//#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <random>
#include <iterator>
#include <numeric>
#include <unordered_map>
#include <map>
#include <unordered_set>
#include <set>
#include <bitset>
//#include <limits>
#include <climits>
#include <queue>
#include <stack>
#include <deque>
#include <tuple>
#include <list>
#include <math.h>
#include <random>
#include <algorithm>
#include <chrono>
#include <iomanip>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
#include <array>
#include <tuple>
#include <functional>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <float.h>

/*
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ordered_set;

ordered_set st;
*/

// g++-13 -std=c++11 codeforce.cpp -o codeforce
// g++ -std=c++11 codeforce.cpp -o codeforce
// ./codeforce <codef.txt

using namespace std;
//using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
//typedef string str;

vector<int> manacher_odd(string s) {
    int n = s.size();
    s = "$" + s + "^";
    vector<int> p(n + 2);
    int l = 1, r = 1;
    for(int i = 1; i <= n; i++) {
        p[i] = max(0, min(r - i, p[l + (r - i)]));
        while(s[i - p[i]] == s[i + p[i]]) {
            p[i]++;
        }
        if(i + p[i] > r) {
            l = i - p[i], r = i + p[i];
        }
    }
    return vector<int>(begin(p) + 1, end(p) - 1);
}
vector<int> manacher(string s) {
    string t;
    for(auto c: s) {
        t += string("#") + c;
    }
    auto res = manacher_odd(t + "#");
    return vector<int>(begin(res) + 1, end(res) - 1);
}

// mt19937_64 rnd(98275314);
// ll gen(){
//     ll x=0;
//     while(x==0){
//         x=rnd();
//     }
//     return x;
// }
vector<int> z_function(string s) {
    int n = s.size();
    vector<int> z(n);
    int l = 0, r = 0;
    for(int i = 1; i < n; i++) {
        if(i < r) {
            z[i] = min(r - i, z[i - l]);
        }
        while(i + z[i] < n && s[z[i]] == s[i + z[i]]) {
            z[i]++;
        }
        if(i + z[i] > r) {
            l = i;
            r = i + z[i];
        }
    }
    return z;
}
/*
template<class T>
struct MaxFlow {
    struct _Edge {
        int to;
        T cap;
        _Edge(int to, T cap) : to(to), cap(cap) {}
    };
    int n;
    std::vector<_Edge> e;
    std::vector<std::vector<int> > g;
    std::vector<int> cur, h;
    MaxFlow() {}
    MaxFlow(int n) {
        init(n);
    }
    void init(int n) {
        this->n = n;
        e.clear();
        g.assign(n, {});
        cur.resize(n);
        h.resize(n);
    }
    bool bfs(int s, int t) {
        h.assign(n, -1);
        std::queue<int> que;
        h[s] = 0;
        que.push(s);
        while (!que.empty()) {
            const int u = que.front();
            que.pop();
            for (int i : g[u]) {
                auto [v, c] = e[i];
                if (c > 0 && h[v] == -1) {
                    h[v] = h[u] + 1;
                    if (v == t) {
                        return true;
                    }
                    que.push(v);
                }
            }
        }
        return false;
    }
    T dfs(int u, int t, T f) {
        if (u == t) {
            return f;
        }
        auto r = f;
        for (int &i = cur[u]; i < int(g[u].size()); ++i) {
            const int j = g[u][i];
            auto [v, c] = e[j];
            if (c > 0 && h[v] == h[u] + 1) {
                auto a = dfs(v, t, std::min(r, c));
                e[j].cap -= a;
                e[j ^ 1].cap += a;
                r -= a;
                if (r == 0) {
                    return f;
                }
            }
        }
        return f - r;
    }
    void addEdge(int u, int v, T c) {
        g[u].push_back(e.size());
        e.emplace_back(v, c);
        g[v].push_back(e.size());
        e.emplace_back(u, 0);
    }
    T flow(int s, int t) {
        T ans = 0;
        while (bfs(s, t)) {
            cur.assign(n, 0);
            ans += dfs(s, t, std::numeric_limits<T>::max());
        }
        return ans;
    }
    std::vector<bool> minCut() {
        std::vector<bool> c(n);
        for (int i = 0; i < n; i++) {
            c[i] = (h[i] != -1);
        }
        return c;
    }
    struct Edge {
        int from;
        int to;
        T cap;
        T flow;
    };
    std::vector<Edge> edges() {
        std::vector<Edge> a;
        for (int i = 0; i < e.size(); i += 2) {
            Edge x;
            x.from = e[i + 1].to;
            x.to = e[i].to;
            x.cap = e[i].cap + e[i + 1].cap;
            x.flow = e[i + 1].cap;
            a.push_back(x);
        }
        return a;
    }
};
*/
// std::mt19937_64 rng {std::chrono::steady_clock::now().time_since_epoch().count()};
const int N=2e5;
vector<int>G[N];
void solve(){
    int n;
    cin>>n;
    vector<int>deg(n);
    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);
        deg[u]++;
        deg[v]++;
    }
    vector<int>idx(n);
    int mx=*max_element(deg.begin(),deg.end());
    iota(idx.begin(),idx.end(),0);
    sort(idx.begin(),idx.end(), [&](int a, int b){
        return deg[a]>deg[b];
    });
    int ans=0;
    for(int j=0;j<n && deg[idx[j]]>=mx-1;++j){
        for(int i=0;i<n;++i){
            if(i==idx[j]){
                continue;
            }
            int adj=0;
            for(int it:G[i]){
                if(it==idx[j]){
                    adj=1;
                    break;
                }
            }
            ans=max(deg[idx[j]]+deg[i]-1-adj,ans);
        }
    }
    cout<<ans<<endl;
    for(int i=0;i<n;++i){
        G[i].clear();
    }
}
int main(int argc, char *argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cout<<std::setprecision(20);
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
}

/*

FOR ICPC style rounds, read all problems! don't get stuck on 1.
*/
/*prvb
nice trick:
up is down?

Fenwick
int lowbit(int i) { // gets the lowest set bit
	return (-i)&i;
}
adds 1 from [1,i];
void bitadd(int i) {
	for(;i<=n;i+=lowbit(i)) bit[i]++;
}
queries [1,i];
int bitqu(int i) {
	int ans=0;
	for(;i;i-=lowbit(i)) ans+=bit[i];
	return ans;
}
*/

Answer: 1


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

void solve() {
  int n; cin >> n;
  vector<pair<int,int>> b;
  set<pair<int,int>> edges;
  vector<int> degree(n,0);

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

    degree[u]++;
    degree[v]++;
    edges.insert(make_pair(u,v));
    edges.insert(make_pair(v,u));
  }

  for (int i = 0; i <= n-1; i++) {
    b.push_back(make_pair(degree[i],i));
  }
  sort(b.begin(), b.end(), greater<pair<int,int>>());

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

  int M = b[0].first, N = b[1].first, K = b[2].first;

  if (M == N && N == K) {
    cout << 2*M - 1 << endl;
    return;
  } else if (M == N && N > K) {
    if (edges.find(make_pair(b[0].second, b[1].second)) != edges.end()) {
      cout << M+N-1 << endl;
    } else {
      cout << 2*M - 1 << endl;
    }
    return;
  } else if (M > N && N == K) {
    int flag = 0;
    for (int i = 1; i < n; i++) {
      if (b[i].first != b[1].first) break;
      if (edges.find(make_pair(b[0].second, b[i].second)) == edges.end()) {
        flag = 1;
        break;
      }
    }

    if (flag) {
      cout << M+N-1 << endl;
    } else {
      cout << M+N-2 << endl;
    }
    return;
  } else {
    cout << M+N-1 << endl;
    return;
  }

  return;
}

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

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

void solve() {
  int n; cin >> n;
  vector<pair<int,int>> b;
  set<pair<int,int>> edges;
  vector<int> degree(n,0);

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

    degree[u]++;
    degree[v]++;
    edges.insert(make_pair(u,v));
    edges.insert(make_pair(v,u));
  }

  for (int i = 0; i <= n-1; i++) {
    b.push_back(make_pair(degree[i],i));
  }
  sort(b.begin(), b.end(), greater<pair<int,int>>());

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

  int M = b[0].first, N = b[1].first, K = b[2].first;

  if (M == N && N == K) {
    cout << 2*M - 1 << endl;
    return;
  } else if (M == N && N > K) {
    if (edges.find(make_pair(b[0].second, b[1].second)) != edges.end()) {
      cout << M+N-2 << endl;
    } else {
      cout << 2*M-1 << endl;
    }
    return;
  } else if (M > N) {
    int flag = 0;
    for (int i = 1; i < n; i++) {
      if (b[i].first != b[1].first) break;
      if (edges.find(make_pair(b[0].second, b[i].second)) == edges.end()) {
        flag = 1;
        break;
      }
    }

    if (flag) {
      cout << M+N-1 << endl;
    } else {
      cout << M+N-2 << endl;
    }
    return;
  }

  return;
}

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

Answer: 2


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

vector<vector<int>> adj;
vector<int> degree;

// void dfs(int node, int par) {
//     for (auto v : adj[node]) {
//         if (v != par) {
//             degree[node]++;
//             dfs(v,node);
//         }
//     }
// }

signed main() {
    int t;
    cin>>t;
    while (t--)
    {

        int n;
        cin>>n;
        // adj.clear();
        // adj.resize(n + 1);
        degree.assign(n+1,0);
        set<pair<int,int>> s;

        for (int i = 1; i < n; i++) {
            int a,b;
            cin >> a>>b;
            degree[a]++;
            degree[b]++;
            // adj[a].push_back(b);
            // adj[b].push_back(a);
            s.insert({a,b});
            s.insert({b,a});
        }

        vector<pair<int,int>> arr;

        for(int i=1;i<=n;i++) arr.push_back({degree[i],i});
        sort(arr.rbegin(),arr.rend());
        int ans=0;

        for(int i=0;i<arr.size();i++){
            for(int j=i+1;j<arr.size();j++){

                if(s.find({arr[i].second,arr[j].second})==s.end()){
                    ans=max(ans,arr[i].first+arr[j].first-1);
                    break;
                }
            }
        }

        for(auto it:s){
            ans=max(ans,degree[it.first]+degree[it.second]-2);
        }
        cout<<ans<<endl;

        //dfs(1, -1);

    }

    return 0;
}

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

vector<vector<int>> adj;
vector<int> degree;

void dfs(int node, int par) {
    for (auto v : adj[node]) {
        if (v != par) {
            degree[node]++;
            dfs(v,node);
        }
    }
}

signed main() {
    int t;
    cin>>t;
    while (t--)
    {

        int n;
        cin>>n;
        adj.clear();
        adj.resize(n + 1);
        degree.assign(n+1,1);

        degree[1]=0;

        for (int i = 1; i < n; i++) {
            int a,b;
            cin >> a>>b;
            adj[a].push_back(b);
            adj[b].push_back(a);
        }

        dfs(1, -1);

        int element=0,deg=0;

        for(int i=1;i<=n;i++){
            if(degree[i]>deg) element=i,deg=degree[i];
        }
        //cout<<deg<<" "<<element<<endl;

        if(deg==n-1) {
            cout<<n-2<<endl;
            continue;
        }

        int ans=0;
        ans+=deg;
        degree[element]=0;

        for(auto v:adj[element]) degree[v]--;

        element=0,deg=0;

        for(int i=1;i<=n;i++){
            if(degree[i]>deg) element=i,deg=degree[i];
        }

        ans+=deg-1;
        cout<<ans<<endl;

    }

    return 0;
}

Answer: 1


#include<iostream>
#include<vector>
#include<set>
#define add(a,b) e[a].push_back(b)
#define rep for(int v:e[i])
#define siz(a) e[a].size()
using namespace std;

const int N=1e6+5;

int t;

vector<int>e[N];
multiset<int>s;

inline void work(){
	s.clear();
	int n,ans=0;
	cin>>n;
	for(int i=0;i<=n;++i)e[i].clear();
	for(int i=1;i<n;++i){
		int u,v;
		cin>>u>>v;
		add(u,v),add(v,u);
	}
	for(int i=1;i<=n;++i){
		s.insert(siz(i));
	}
	for(int i=1;i<=n;++i){
		s.erase(s.find(siz(i)));
		rep{
			s.erase(s.find(siz(v)));
			s.insert(siz(v)-1);
		}
		ans=max(ans,(int)siz(i)+*s.rbegin()-1);
		s.insert(siz(i));
		rep{
			s.erase(s.find(siz(v)-1));
			s.insert(siz(v));
		}
	}
	cout<<ans<<"\n";
	return ;
}

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

#include<iostream>
#include<vector>
#include<set>
#define add(a,b) e[a].push_back(b)
#define rep for(int v:e[i])
#define siz(a) e[a].size()
using namespace std;

const int N=1e5+5;

int t;

vector<int>e[N];
multiset<int>s;

inline void work(){
	s.clear();
	for(int i=0;i<N;++i)e[i].clear();
	int n,ans=0;
	cin>>n;
	for(int i=1;i<n;++i){
		int u,v;
		cin>>u>>v;
		add(u,v),add(v,u);
	}
	for(int i=1;i<=n;++i){
		s.insert(siz(i));
	}
	for(int i=1;i<=n;++i){
		s.erase(s.find(siz(i)));
		rep{
			s.erase(s.find(siz(v)));
			s.insert(siz(v)-1);
		}
		ans=max(ans,(int)siz(i)+*s.rbegin()-1);
		s.insert(siz(i));
		rep{
			s.erase(s.find(siz(v)-1));
			s.insert(e[v].size());
		}
	}
	cout<<ans<<"\n";
	return ;
}

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

Answer: 1


#include <bits/stdc++.h>

using namespace std;
const int N = 2e5 + 5;
int t;
int n, u, v, ans, d[N];
set<pair<int, int> > c;
vector<int> a[N];
void dfs(int u, int p) {
    for(auto& v : a[u]) {
        if(v != p) {
            dfs(v, u);
            ans = max(ans, (int) a[v].size() + (int) a[u].size() - 2);
        }
    }
}
bool cmp(int x, int y) {
    if(a[x].size() == a[y].size())return x < y;
    return a[x].size() > a[y].size();
}
void solve() {
    ans = 0;
    dfs(1, 0);
    sort(d + 1, d + n + 1, cmp);
    for(int i = 1; i <= n; i++) {
        for(int j = i + 1; j <= n; j++) {
            if(c.find({d[i], d[j]}) == c.end()) {
                ans = max(ans, (int) a[d[i]].size() + (int) a[d[j]].size() - 1);
                break;
            }
        }
    }
    cout << ans << '\n';
}
void input() {
	cin >> t;
	while(t--) {
        cin >> n;
        c.clear();
        for(int i = 1; i <= n; i++) {
            a[i].clear();
            d[i] = i;
        }
        for(int i = 1; i <= n - 1; i++) {
            cin >> u >> v;
            c.insert({u, v});
            c.insert({v, u});
            a[u].push_back(v);
            a[v].push_back(u);
        }
		solve();
	}
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	input();
	return 0;
}

#include <bits/stdc++.h>

using namespace std;
const int N = 2e5 + 5;
int t;
int n, u, v, ans, d[N], d1[N];
vector<int> a[N];
void dfs(int u, int p) {
    d[u] = a[u].size();
    int mx = 0, mx1 = 0;
    for(auto& v : a[u]) {
        if(v != p) {
            dfs(v, u);
            d[u] = max(d[u], d[v]);
            d1[u] = max(d1[u], (int) a[v].size());
            mx1 = max(mx1, d1[v]);
            ans = max(ans, (int) a[v].size() + (int) a[u].size() - 2);
            ans = max(ans, mx + d[v] - 1);
            mx = max(mx, d[v]);
        }
    }
    ans = max(ans, mx1 + (int) a[u].size() - 1);
}
void solve() {
    ans = 0;
    dfs(1, 0);
    cout << ans << '\n';
}
void input() {
	cin >> t;
	while(t--) {
        cin >> n;
        for(int i = 1; i <= n; i++) {
            a[i].clear();
            d[i] = 0;
            d1[i] = 0;
        }
        for(int i = 1; i <= n - 1; i++) {
            cin >> u >> v;
            a[u].push_back(v);
            a[v].push_back(u);
        }
		solve();
	}
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	input();
	return 0;
}

Answer: 1


import io
import os
import sys

inf = 10 ** 18
mod = 10 ** 9 + 7

ONLINE_JUDGE = __debug__

if ONLINE_JUDGE:
    R = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    def _input() -> str:
        return R().decode()
else:
    R = sys.stdin.readline

    def _input() -> str:
        return R()

def get_int() -> int:
    return int(_input())

def get_str() -> str:
    return _input().strip()

def get_int_list() -> list[int]:
    return list(map(int, _input().strip().split()))

def init_matrix(n_, m_, value_=0) -> list[list]:
    return [[value_] * m_ for _ in range(n_)]

def solve() -> None:
    n = get_int()

    g = init_matrix(n, 0)
    cnt = [0] * n
    pairs = set()
    for i in range(n - 1):
        u, v = get_int_list()
        u -= 1
        v -= 1
        g[v].append(u)
        g[u].append(v)
        cnt[u] += 1
        cnt[v] += 1
        pairs.add((u, v))
        pairs.add((v, u))

    order = sorted(
        range(len(cnt)),
        key=lambda x: cnt[x],
        reverse=True,
    )
    u, v = order[:2]
    h = []
    for i in range(n):
        if cnt[i] == cnt[v]:
            h.append(i)

    if cnt[u] != cnt[v]:
        for w in h:
            if (u, w) not in pairs:
                print(cnt[u] + cnt[v] - 1)
                return

        print(cnt[u] + cnt[v] - 2)
    else:
        for i in range(len(h)):
            for j in range(i + 1, len(h)):
                if (h[i], h[j]) not in pairs:
                    print(cnt[u] + cnt[v] - 1)
                    return

        print(cnt[u] + cnt[v] - 2)

for _ in range(get_int()):
    solve()

import io
import os
import sys

inf = 10 ** 18
mod = 10 ** 9 + 7

ONLINE_JUDGE = __debug__

if ONLINE_JUDGE:
    R = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    def _input() -> str:
        return R().decode()
else:
    R = sys.stdin.readline

    def _input() -> str:
        return R()

def get_int() -> int:
    return int(_input())

def get_str() -> str:
    return _input().strip()

def get_int_list() -> list[int]:
    return list(map(int, _input().strip().split()))

def init_matrix(n_, m_, value_=0) -> list[list]:
    return [[value_] * m_ for _ in range(n_)]

def solve() -> None:
    n = get_int()

    g = init_matrix(n, 0)
    cnt = [0] * n
    pairs = set()
    for i in range(n - 1):
        u, v = get_int_list()
        u -= 1
        v -= 1
        g[v].append(u)
        g[u].append(v)
        cnt[u] += 1
        cnt[v] += 1
        pairs.add((u, v))
        pairs.add((v, u))

    order = sorted(
        range(len(cnt)),
        key=lambda x: cnt[x],
        reverse=True,
    )
    u, v = order[:2]
    h = []
    for i in range(n):
        if cnt[i] == cnt[v]:
            h.append(i)

    if cnt[u] != cnt[v]:
        for w in h:
            if (u, w) not in pairs:
                print(cnt[u] + cnt[v] - 1)
                return

        print(cnt[u] + cnt[v] - 2)
    else:
        for i in range(len(h)):
            for j in range(i + 1, len(h)):
                if (i, j) not in pairs:
                    print(cnt[u] + cnt[v] - 1)
                    return

        print(cnt[u] + cnt[v] - 2)

for _ in range(get_int()):
    solve()

Answer: 1


#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <string.h>
#define ll long long
#define pii pair<int,int>
using namespace std;

const int LM=200100;
int n;
vector<int>G[LM];

int C(int x, int y){
    for(int i:G[x])if(y==i)return 1;
    return 0;
}

void solve(){
    scanf("%d",&n);
    for(int i=1; i<=n; i++)G[i].clear();
    for(int i=1; i<n; i++){
        int u,v;
        scanf("%d%d",&u,&v);
        G[u].push_back(v);
        G[v].push_back(u);
    }
    int si[LM], Ms=0;
    vector<int>v[LM];
    for(int i=1; i<=n; i++){
        si[i]=G[i].size();
        Ms=max(Ms,si[i]);
        v[si[i]].push_back(i);
    }
    int MsSi=v[Ms].size();
    if(MsSi>=3)
        printf("%d\n",Ms*2-1);
    if(MsSi==2){
        printf("%d\n",Ms*2-C(v[Ms][0],v[Ms][1])-1);
    }
    else{
        int ws=Ms-1;
        while(v[ws].size()==0)ws--;
        for(int i:v[ws]){
            if(C(i,v[Ms][0])==0){
                printf("%d\n",Ms+ws-1);
                return;
            }
        }
        printf("%d\n",Ms+ws-2);
    }
}

int main(){
    int tc;
    scanf("%d", &tc);
    for(;tc>0;tc--)solve();
}

#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <string.h>
#define ll long long
#define pii pair<int,int>
using namespace std;

const int LM=200100;
int n;
vector<int>G[LM];
set<int> S[LM];
vector<int>v[LM];

int C(int x, int y){
    return S[x].find(y)!=S[x].end();
}

void solve(){
    scanf("%d",&n);
    for(int i=1; i<=n; i++)G[i].clear(),v[i].clear(),S[i].clear();
    for(int i=1; i<n; i++){
        int x,y;
        scanf("%d%d",&x,&y);
        G[x].push_back(y);
        G[y].push_back(x);
        S[x].insert(y);
        S[y].insert(x);
    }
    int si[LM], Ms=0;

    for(int i=1; i<=n; i++){
        si[i]=G[i].size();
        Ms=max(Ms,si[i]);
        v[si[i]].push_back(i);
    }

    int MsSi=v[Ms].size();
    if(MsSi>=3)
        printf("%d\n",Ms*2-1);
    else if(MsSi==2){
        printf("%d\n",Ms*2-C(v[Ms][0],v[Ms][1])-1);
    }
    else{
        int ws=Ms-1;
        while(v[ws].empty())ws--;
        for(int i:v[ws]){
            if(C(i,v[Ms][0])==0){
                printf("%d\n",Ms+ws-1);
                return;
            }
        }
        printf("%d\n",Ms+ws-2);
    }
}

int main(){
    int tc;
    scanf("%d", &tc);
    for(;tc>0;tc--)solve();
}

Answer: 2


#include <bits/stdc++.h>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;

using namespace std;

// typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key
#define int long long
#define pb push_back
#define vi vector<int>
#define loop(i, n1, n) for (int i = n1; i < n; i++)
#define revloop(i, n, n1) for (int i = n; i >= n1; i--)
#define endl "\n"
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
#define sortv(v) sort(v.begin(), v.end())
#define pii pair<int, int>
#define vinp(v, n)              \
    for (int i = 0; i < n; i++) \
    {                           \
        int k;                  \
        cin >> k;               \
        v.pb(k);                \
    }
#define mii map<int, int>
// #define m 1e9+7
#define nl cout << endl
#define vdebug(v)         \
    for (auto i : v)      \
        cout << i << " "; \
    nl

#define vall(v) v.begin(), v.end()
#define vsort(v) sort(vall(v))
#define print(v) cout << v << endl;
double pi = 2 * acos(0.0);
int max(int a, int b)
{
    if (a > b)
        return a;
    else
        return b;
}
int min(int a, int b)
{
    if (a > b)
        return b;
    else
        return a;
}
bool isPalindrome(string S)
{

    string P = S;

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

    if (S == P)
    {

        return 1;
    }

    else
    {

        return 0;
    }
}
// void build(vector<int> v){
//     int n=v.size();
//     vector<vector<int>> s(n,vector<int>(17));
//     for(int i=0;i<n;i++){
//         s[i][0]=v[i];
//     }
//     for(int j=1;(1<<j)<=n;j++){
//         for(int i=0;i+(1<<j)<=n;i++){
//             s[i][j]=s[i][j-1] | s[i+ (1<<(j-1))][j-1];
//         }
//     }
//     //query
//     int lo=0,hi=5;
//     int len=hi-lo+1;
//     int k=log2(len);
//     int query=(s[lo][k] | s[hi-(1<<k)+1][k]);

// }

int binarySearch(vector<int> &arr, int target)
{
    int left = 0, right = arr.size() - 1;
    while (left <= right)
    {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target)
        {
            return mid;
        }
        else if (arr[mid] < target)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }
    return -1;
}

int RSB(int n)
{
    return log2(n & -n);
}

int factorial(int b)
{
    if (b == 1 || b == 0)
        return 1;
    return (b)*factorial(b - 1);
}

void multiply(int a[3][3], int b[3][3])
{
    int mul[3][3];
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            mul[i][j] = 0;
            for (int k = 0; k < 3; k++)
            {
                mul[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            a[i][j] = mul[i][j];
        }
    }
}

int power(int F[3][3], int n)
{
    int M[3][3] = {{1, 1, 0}, {1, 0, 0}, {0, 1, 0}};
    if (n == 1)
        return F[0][0] + F[0][1];
    power(F, n / 2);
    multiply(F, F);
    if (n % 2 != 0)
        multiply(F, M);
    return F[0][0] + F[0][1];
}

int fibo(int n)
{
    --n;
    int F[3][3] = {{1, 1, 0}, {1, 0, 0}, {0, 1, 0}};
    if (n == 0)
        return 0;
    if (n == 1 || n == 2)
        return 1;
    return power(F, n - 2);
}
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
int lcm(int a, int b)
{
    return (a * b / gcd(a, b));
}
int prime(int n)
{
    int x = 2;

    while (x <= sqrt(n))
    {
        if ((n % x) == 0)
        {

            return x;
        }
        x++;
    }
    return -1;
}

double codist(int x1, int y1, int x2, int y2)
{
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
int NC2(int x)
{
    return max(x * (x - 1) / 2, 0);
}
int NC3(int x)
{
    return max(x * (x - 1) * (x - 2) / 6, 0);
}
void fact(int n, vector<int> &v)
{
    for (int i = 1; i <= sqrt(n); i++)
    {
        if (n % i == 0)
        {
            v.pb(i);
            v.pb(n / i);
        }
    }
}

bool check(int k, int n, const vector<vector<int>> &op)
{
    int chec = -1;
    for (int i = 0; i <= n - k; ++i)
    {
        int j = log2(k);
        int o = op[i][j] | op[i + k - (1 << j)][j];
        if (chec == -1)
            chec = o;
        if (chec != o)
            return false;
    }
    return true;
}

void solve()
{
    int n;
    cin >> n;
    mii mp;
    mii adj;
    for (int i = 0; i < n - 1; i++)
    {
        int a, b;
        cin >> a >> b;
        mp[a]++;
        mp[b]++;
        adj[a] = b;
        adj[b] = a;
    }
    priority_queue<pii> pq;
    for (auto i : mp)
    {
        pq.push({i.second, i.first});
    }

    int x = pq.top().first;
    int e1 = pq.top().second;
    pq.pop();
    int y = pq.top().first;
    int e2 = pq.top().second;
    if (adj[e1] == e2)
        cout << x + y - 2 << endl;
    else
        cout << x + y - 1 << endl;
}

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

#include <bits/stdc++.h>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;

using namespace std;

// typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key
#define int long long
#define pb push_back
#define vi vector<int>
#define loop(i, n1, n) for (int i = n1; i < n; i++)
#define revloop(i, n, n1) for (int i = n; i >= n1; i--)
#define endl "\n"
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
#define sortv(v) sort(v.begin(), v.end())
#define pii pair<int, int>
#define vinp(v, n)              \
    for (int i = 0; i < n; i++) \
    {                           \
        int k;                  \
        cin >> k;               \
        v.pb(k);                \
    }
#define mii map<int, int>
// #define m 1e9+7
#define nl cout << endl
#define vdebug(v)         \
    for (auto i : v)      \
        cout << i << " "; \
    nl

#define vall(v) v.begin(), v.end()
#define vsort(v) sort(vall(v))
#define print(v) cout << v << endl;
double pi = 2 * acos(0.0);
int max(int a, int b)
{
    if (a > b)
        return a;
    else
        return b;
}
int min(int a, int b)
{
    if (a > b)
        return b;
    else
        return a;
}
bool isPalindrome(string S)
{

    string P = S;

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

    if (S == P)
    {

        return 1;
    }

    else
    {

        return 0;
    }
}
// void build(vector<int> v){
//     int n=v.size();
//     vector<vector<int>> s(n,vector<int>(17));
//     for(int i=0;i<n;i++){
//         s[i][0]=v[i];
//     }
//     for(int j=1;(1<<j)<=n;j++){
//         for(int i=0;i+(1<<j)<=n;i++){
//             s[i][j]=s[i][j-1] | s[i+ (1<<(j-1))][j-1];
//         }
//     }
//     //query
//     int lo=0,hi=5;
//     int len=hi-lo+1;
//     int k=log2(len);
//     int query=(s[lo][k] | s[hi-(1<<k)+1][k]);

// }

int binarySearch(vector<int> &arr, int target)
{
    int left = 0, right = arr.size() - 1;
    while (left <= right)
    {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target)
        {
            return mid;
        }
        else if (arr[mid] < target)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }
    return -1;
}

int RSB(int n)
{
    return log2(n & -n);
}

int factorial(int b)
{
    if (b == 1 || b == 0)
        return 1;
    return (b)*factorial(b - 1);
}

void multiply(int a[3][3], int b[3][3])
{
    int mul[3][3];
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            mul[i][j] = 0;
            for (int k = 0; k < 3; k++)
            {
                mul[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            a[i][j] = mul[i][j];
        }
    }
}

int power(int F[3][3], int n)
{
    int M[3][3] = {{1, 1, 0}, {1, 0, 0}, {0, 1, 0}};
    if (n == 1)
        return F[0][0] + F[0][1];
    power(F, n / 2);
    multiply(F, F);
    if (n % 2 != 0)
        multiply(F, M);
    return F[0][0] + F[0][1];
}

int fibo(int n)
{
    --n;
    int F[3][3] = {{1, 1, 0}, {1, 0, 0}, {0, 1, 0}};
    if (n == 0)
        return 0;
    if (n == 1 || n == 2)
        return 1;
    return power(F, n - 2);
}
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
int lcm(int a, int b)
{
    return (a * b / gcd(a, b));
}
int prime(int n)
{
    int x = 2;

    while (x <= sqrt(n))
    {
        if ((n % x) == 0)
        {

            return x;
        }
        x++;
    }
    return -1;
}

double codist(int x1, int y1, int x2, int y2)
{
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
int NC2(int x)
{
    return max(x * (x - 1) / 2, 0);
}
int NC3(int x)
{
    return max(x * (x - 1) * (x - 2) / 6, 0);
}
void fact(int n, vector<int> &v)
{
    for (int i = 1; i <= sqrt(n); i++)
    {
        if (n % i == 0)
        {
            v.pb(i);
            v.pb(n / i);
        }
    }
}

bool check(int k, int n, const vector<vector<int>> &op)
{
    int chec = -1;
    for (int i = 0; i <= n - k; ++i)
    {
        int j = log2(k);
        int o = op[i][j] | op[i + k - (1 << j)][j];
        if (chec == -1)
            chec = o;
        if (chec != o)
            return false;
    }
    return true;
}

void solve()
{
    int n;
    cin >> n;
    vector<int> g[n + 1];
    for (int i = 0; i < n - 1; i++)
    {
        int x, y;
        cin >> x >> y;
        g[x].pb(y);
        g[y].pb(x);
    }
    int ans = 0, mx = 0, id;
    for (int i = 1; i <= n; i++)
    {
        int sz = g[i].size();
        mx = max(mx, sz);
        if (g[i].size() == mx)
            id = i;
    }
    int cnt = 0;
    for (int i = 1; i <= n; i++)
    {
        int sz = g[i].size();
        if (sz == mx)
            cnt++;
    }
    if (cnt >= 3)
    {
        cout << 2 * mx - 1 << endl;
        return;
    }
    ans += mx;
    set<int> se;
    mx = 0;
    for (auto x : g[id])
        se.insert(x);
    for (int i = 1; i <= n; i++)
    {
        if (i == id)
            continue;
        int sz = g[i].size();
        if (se.find(i) != se.end())
        {
            mx = max(mx, sz - 1);
        }
        else
            mx = max(mx, sz);
    }

    ans += (mx - 1);
    cout << ans << endl;
}

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

Answer: 2


#include <bits/stdc++.h>
#include <iostream>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef long double ld;
typedef vector<vector<ll>> VI;
ll mod = 1e9 + 7;
const ll INF = 5e18;

vi inputVector(int n)
{
  vi vec(n);
  for (int i = 0; i < n; ++i)
  {
    cin >> vec[i];
  }
  return vec;
}
vi inputVector2(int n)
{
  vi vec(n + 1);
  for (int i = 1; i <= n; ++i)
  {
    cin >> vec[i];
  }
  return vec;
}
VI input2D(ll n, ll m)
{
  VI vec(n, vi(m));
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < m; j++)
    {
      cin >> vec[i][j];
    }
  }
  return vec;
}
ll power(ll x, ll y)
{
  ll res = 1;
  while (y > 0)
  {
    if (y % 2 == 1)
      res = ((res % mod) * (x % mod)) % mod;

    y = y >> 1;
    x = ((x % mod) * (x % mod)) % mod;
  }
  return res % mod;
}
ll fn(ll node, set<pair<ll, ll>> &st, ll n, vi &in)
{
  ll ans = 0;
  for (ll i = 1; i <= n; i++)
  {
    if (i == node)
    {
      continue;
    }
    if (st.find({node, i}) == st.end())
    {
      ans = max(ans, 1 + in[node] - 1 + in[i] - 1);
    }
    else
    {
      ans = max(ans, 1 + in[node] - 1 + in[i] - 1 - 1);
    }
  }
  return ans;
}
int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ll t;
  cin >> t;
  while (t--)
  {
    ll n;
    cin >> n;
    VI adj(n + 1);
    vi in(n + 1, 0);
    set<pair<ll, ll>> st;
    for (ll i = 1; i < n; i++)
    {
      ll x, y;
      cin >> x >> y;
      // adj[x].push_back(y);
      // adj[y].push_back(x);
      st.insert({x, y});
      st.insert({y, x});
      in[x]++;
      in[y]++;
    }
    ll maxi = 0, smaxi = 0;
    ll n1 = 0, n2 = 0;
    for (ll i = 1; i <= n; i++)
    {
      if (in[i] >= maxi)
      {
        n2 = n1;
        smaxi = maxi;
        maxi = in[i];
        n1 = i;
      }
      else if (in[i] > smaxi)
      {
        smaxi = in[i];
        n2 = i;
      }
    }
    ll ans = fn(n1, st, n, in);
    ans = max(ans, fn(n2, st, n, in));
    cout << ans << endl;
  }
}

#include <bits/stdc++.h>
#include <iostream>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef long double ld;
typedef vector<vector<ll>> VI;
ll mod = 1e9 + 7;
const ll INF = 5e18;

vi inputVector(int n)
{
  vi vec(n);
  for (int i = 0; i < n; ++i)
  {
    cin >> vec[i];
  }
  return vec;
}
vi inputVector2(int n)
{
  vi vec(n + 1);
  for (int i = 1; i <= n; ++i)
  {
    cin >> vec[i];
  }
  return vec;
}
VI input2D(ll n, ll m)
{
  VI vec(n, vi(m));
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < m; j++)
    {
      cin >> vec[i][j];
    }
  }
  return vec;
}
ll power(ll x, ll y)
{
  ll res = 1;
  while (y > 0)
  {
    if (y % 2 == 1)
      res = ((res % mod) * (x % mod)) % mod;

    y = y >> 1;
    x = ((x % mod) * (x % mod)) % mod;
  }
  return res % mod;
}

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ll t;
  cin >> t;
  while (t--)
  {
    ll n;
    cin >> n;
    VI adj(n + 1);
    vi in(n + 1, 0);
    for (ll i = 1; i < n; i++)
    {
      ll x, y;
      cin >> x >> y;
      adj[x].push_back(y);
      adj[y].push_back(x);
      in[x]++;
      in[y]++;
    }
    ll ans = 1, node = 0;
    for (ll i = 1; i <= n; i++)
    {
      if (in[i] > in[node])
      {
        node = i;
      }
    }
    ans += in[node] - 1;
    in[node] = 0;
    for (auto it : adj[node])
    {
      in[it]--;
    }
    node = 0;
    for (ll i = 1; i <= n; i++)
    {
      if (in[i] > in[node])
      {
        node = i;
      }
    }
    ans += in[node] - 1;
    cout << ans << endl;
  }
}

Answer: 1


#include <bits/stdc++.h>
#define endl "\n"
#define all(a) a.begin(), a.end()
#define ll long long
#define ull unsigned long long
#define inf 0x7fffffff;
#define rep(i, l, r) for (int i = l; i <= r; ++i)
#define rrp(i, l, r) for (int i = l; i >= r; --i)
#define fucking_go(x) \
    int t;            \
    cin >> t;         \
    while (t--)       \
    x()
using namespace std;
using vi = vector<int>;
using vl = vector<ll>;
using vvi = vector<vector<int>>;
using vvl = vector<vector<ll>>;
using vpii = vector<pair<int, int>>;
using vpll = vector<pair<ll, ll>>;
using pii = pair<int, int>;
const ll mod = 1e9 + 7;
// const ll mod = 998244353;
const ll INF = 1e18;

int n;
set<int> g[200010];
int a[200010];
void solve()
{
    cin >> n;
    for (int i = 1; i <= n; i++) g[i].clear(), a[i] = 0;
    for (int i = 1; i <= n - 1; i++)
    {
        int u, v;
        cin >> u >> v;
        g[u].insert(v);
        g[v].insert(u);
        a[u]++;
        a[v]++;
    }
    multiset<int> st;
    for (int i = 1; i <= n; i++)
    {
        st.insert(a[i]);
    }
    int ans = 0;
    for (int i = 1; i <= n; i++)
    {
        int now = 0;
        st.erase(st.find(a[i]));
        for (int v : g[i])
        {
            st.erase(st.find(a[v]));
            st.insert(a[v] - 1);
        }
        now += a[i];
        now += (*st.rbegin()) - 1;
        for (int v : g[i])
        {
            st.erase(st.find(a[v] - 1));
            st.insert(a[v]);
        }
        st.insert(a[i]);
        ans = max(ans, now);
    }
    cout << ans << endl;
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    // helper();
    // init();
    fucking_go(solve);
    // solve();

    return 0;
}

#include <bits/stdc++.h>
#define endl "\n"
#define all(a) a.begin(), a.end()
#define ll long long
#define ull unsigned long long
#define inf 0x7fffffff;
#define rep(i, l, r) for(int i = l; i <= r; ++i)
#define rrp(i, l, r) for(int i = l; i >= r; --i)
#define fucking_go(x) int t; cin >> t; while(t--) x()
using namespace std;
using vi = vector<int>;
using vl = vector<ll>;
using vvi = vector<vector<int> >;
using vvl = vector<vector<ll> >;
using vpii = vector<pair<int, int> >;
using vpll = vector<pair<ll, ll> >;
using pii = pair<int, int>;
const ll mod = 1e9 + 7;
//const ll mod = 998244353;
const ll INF = 1e18;

int n;
set<int> g[200010];
void solve() {
    cin >> n;
    for (int i = 1; i <= n; i++) g[i].clear();
    for (int i = 1; i <= n - 1; i++) {
        int u, v;
        cin >> u >> v;
        g[u].insert(v);
        g[v].insert(u);
    }
    // if (n == 2) {
    //     cout << 0 << endl;
    //     return;
    // }
    vi del(n + 1);
    vi cnt(n + 1);
    for (int i = 1; i <= n; i++) {
        if (g[i].size() == 1) cnt[(*g[i].begin())]++;
    }
    int mx = -1, index = 0;
    for (int i = 1; i <= n; i++) {
        if (cnt[i] > mx) {
            mx = cnt[i];
            index = i;
        }
    }
    del[index] = 1;
    vi tmp;
    for (int x : g[index]) {
        tmp.push_back(x);
    }
    for (int x : tmp) {
        g[x].erase(index);
        g[index].erase(x);
        if (g[x].size() == 1) {
            cnt[(*g[x].begin())]++;
        }
    }
    mx = -1, index = 0;
    for (int i = 1; i <= n; i++) {
        if (del[i] == 0) {
            if (cnt[i] > mx) {
                mx = cnt[i];
                index = i;
            }
        }
    }
    if (mx == -1) {
        for (int i = 1; i <= n; i++) {
            if (del[i] == 0) {
                del[i] = 1;
                break;
            }
        }
    }
    else {
        del[index] = 1;
        tmp.clear();
        for (int x : g[index]) {
            tmp.push_back(x);
        }
        for (int x : tmp) {
            g[index].erase(x);
            g[x].erase(index);
        }
    }
    int ans = 0;
    vi flag(n + 1);
    queue<int> q;
    for (int i = 1; i <= n; i++) {
        if (del[i] == 0) {
            q.push(i);
            ans++;
            while (!q.empty()) {
                int x = q.front();
                q.pop();
                del[x] = 1;
                for (int y : g[x]) {
                    if (del[y] == 0) {
                        q.push(y);
                    }
                }
            }
        }
    }
    cout << ans << endl;
}

int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
// helper();
// init();
fucking_go(solve);
//solve();

return 0;
}

Answer: 1


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    cin >> t;
    while (t--){
        int n;
        cin >> n;
        vector<pair<int,int>> edges;
        int counting[200015]; // counting[i] denotes the number of edges that connects to edge i
        bool adj[200015]; // adj[i] denotes whether node i is adjacent to the maxnode
        for (int i=1; i<=n; i++){ // reset counting and adj
            counting[i] = 0;
            adj[i] = false;
        }
        vector<pair<int,int>> cnt; // counting, index
        int dem = 1; // number of connected components
        vector<int> maxnode2;

        for (int i=1; i<n; i++){
            int x, y;
            cin >> x >> y;
            edges.push_back({x,y});
            counting[x]++;
            counting[y]++;
        }

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

        int maxnode = cnt.back().second;
        for (auto edge: edges){
            int x = edge.first;
            int y = edge.second;

            if (x == maxnode || y == maxnode) adj[x + y - maxnode] = true;
        }

        for (int i=cnt.size() - 2; i >= 0; i--){
            if (cnt[i].first == cnt[cnt.size() - 2].first) maxnode2.push_back(cnt[i].second);
        }

        dem = cnt.back().first + counting[maxnode2[0]] - 1;

        if (cnt.back().first == counting[maxnode2[0]] && maxnode2.size() > 1) dem += 0; // more than 3 max nodes so ignore updates
        else{
            bool check = false; // true = there is a node in maxnode2 that doesnt directly connect to maxnode

            for (auto x : maxnode2){
                if (adj[x] == false) check = true;
            }

            if (!check) dem--;
        }

        // clearing for next test case
        cnt.clear();
        edges.clear();
        maxnode2.clear();

        cout << dem << endl;
    }

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    cin >> t;
    while (t--){
        int n;
        cin >> n;
        vector<pair<int,int>> edges;
        int counting[200015]; // counting[i] denotes the number of edges that connects to edge i
        bool adj[200015]; // adj[i] denotes whether node i is adjacent to the maxnode
        for (int i=1; i<=n; i++){ // reset counting and adj
            counting[i] = 0;
            adj[i] = false;
        }
        vector<pair<int,int>> cnt; // counting, index
        int dem = 1; // number of connected components
        vector<int> maxnode2;

        for (int i=1; i<n; i++){
            int x, y;
            cin >> x >> y;
            edges.push_back({x,y});
            counting[x]++;
            counting[y]++;
        }

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

        int maxnode = cnt.back().second;
        for (auto edge: edges){
            int x = edge.first;
            int y = edge.second;

            if (x == maxnode || y == maxnode) adj[x + y - maxnode] = true;
        }

        for (int i=cnt.size() - 2; i >= 0; i--){
            if (cnt[i].first == cnt[cnt.size() - 2].first) maxnode2.push_back(cnt[i].second);
        }

        dem = cnt.back().first + counting[maxnode2[0]] - 1;

        if (cnt.back().first == counting[maxnode2[0]] && maxnode2.size() > 1) continue; // more than 3 max nodes
        else{
            bool check = false; // true = there is a node in maxnode2 that doesnt directly connect to maxnode

            for (auto x : maxnode2){
                if (adj[x] == false) check = true;
            }

            if (!check) dem--;
        }

        // clearing for next test case
        cnt.clear();
        edges.clear();
        maxnode2.clear();

        cout << dem << endl;
    }

    return 0;
}

Answer: 1


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

#include<bits/stdc++.h>

#define NoTLE ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ld long double
#define ll long long
#define F first
#define S second
#define pb push_back
#define all(x) x.begin(),x.end()
#define nl '\n'
#define YES cout << "YES"
#define NO cout << "NO"
#define fx(i) fixed<<setprecision(i)

using namespace std;

const int MOD = 1e9+7 ;
const int MOD2 = 998244353 ;
const ld eps = 1e-10;
const ld pi = acos(-1) ;

void noBrainer ()
{

}

void new_test( )
{

}

int center( map < int , vector < int > > & tree )
{
	vector < int > leafs ;
	vector < int > dgr ( tree.size() + 1 );
	for ( auto el : tree )
	{
		dgr[el.F] = el.S.size() ;
	}
	for ( int i = 1 ; i <= tree.size() ; i++ )
	{
		if ( dgr[i] == 1 ) leafs.pb(i) ;
	}
	int ans = 2 ;
	while ( leafs.size() > 0 )
	{
		vector < int > new_leafs ;
		for ( auto el : leafs )
		{
			for ( auto nd : tree[el] )
			{
				dgr[nd] -- ;
				if ( dgr[nd] == 1 ) new_leafs.pb(nd) ;
			}
		}
		leafs = new_leafs ;
		if ( leafs.size() > 1 ) ans += 2 ;
		else if ( leafs.size() == 1 ) ans += 1 ;
	}
	return leafs[0] ;
}

void solve()
{
	int n ; cin >> n ;
	map < int , vector < int > > tree ;
	vector < int > dig ( n + 1 ) ;
	int cur = 0 ;
	int ma = 0 ;
	for ( int i = 0 ; i < n - 1 ; i++ )
	{
		int a , b ; cin >> a >> b ;
		tree[a].pb(b) ;
		tree[b].pb(a) ;
		dig[a]++ ;
		dig[b]++ ;
		if ( ma < dig[a] )
		{
			ma = dig[a] ;
			cur = a ;
		}
		if ( ma < dig[b] )
		{
			ma = dig[b] ;
			cur = b ;
		}
	}
	int tmp = center(tree) ;
	if ( tmp == cur )
	{
		for ( int i = 1 ; i <= n ; i++ )
		{
			if ( dig[i] == ma && i != tmp )
			{
				cur = i ;
			}
		}
	}

	int ans = ma - 1 ;
	for ( auto el : tree[cur] )
	{
		dig[el]-- ;
	}
	int mn = 0 ;
	for ( int i = 1 ; i <= n ; i++ )
	{
		if ( i != cur )
		mn = max ( mn , dig[i] ) ;
	}
	ans += mn ;
	cout << ans ;
}

signed main()
{
    NoTLE
    //freopen( "input.txt" , "r" , stdin );
    //freopen( "output.txt" , "w" , stdout );
    int T = 1;
    cin >> T ;
    //int X = T;
    while( T-- )
    {
    	// int ctest = X-T ;
        //noBrainer() ;
        solve();
        cout << nl ;
    }
    return 0;
}

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

#include<bits/stdc++.h>

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

#define ld long double
#define ll long long
#define F first
#define S second
#define pb push_back
#define all(x) x.begin(),x.end()
#define nl '\n'
#define YES cout << "YES"
#define NO cout << "NO"
#define fx(i) fixed<<setprecision(i)

using namespace std;

const int MOD = 1e9+7 ;
const int MOD2 = 998244353 ;
const ld eps = 1e-10;
const ld pi = acos(-1) ;

void noBrainer ()
{

}

void new_test( )
{

}

void center( map < int , vector < int > > & tree , vector < int >& lvl )
{
	vector < int > leafs ;
	vector < int > dgr ( tree.size() + 1 );
	for ( auto el : tree )
	{
		dgr[el.F] = el.S.size() ;
	}
	for ( int i = 1 ; i <= tree.size() ; i++ )
	{
		if ( dgr[i] == 1 ) leafs.pb(i) , lvl[i] = 1 ;
	}
	int ans = 2 ;
	while ( leafs.size() > 0 )
	{

		vector < int > new_leafs ;
		for ( auto el : leafs )
		{
			for ( auto nd : tree[el] )
			{
				dgr[nd] -- ;
				if ( dgr[nd] == 1 ) new_leafs.pb(nd) , lvl[nd] = lvl[el]+1 ;
			}
		}
		leafs = new_leafs ;
		if ( leafs.size() > 1 ) ans += 2 ;
		else if ( leafs.size() == 1 ) ans += 1 ;
	}
}

void solve()
{
	int n ; cin >> n;
	map < int , vector < int > > tree ;
	vector < int > dgr ( n + 1 ) ;
	for ( int i = 1 ; i < n ; i++ )
	{
		int a , b ; cin >> a >> b ;
		tree[a].pb(b) ;
		tree[b].pb(a) ;
		dgr[a]++ ;
		dgr[b]++ ;
	}

	vector < int > lvl ( n + 1 ) ;
	center( tree , lvl ) ;

	int mnl = 1e6 , mx = 0 ;
	int del = 0 ;
	for ( int i = 1 ; i <= n ; i++ )
	{
		if ( dgr[i] > mx )
		{
			mx = dgr[i] ;
			mnl = lvl[i] ;
			del = i ;
		}
		if ( dgr[i] == mx && mnl > lvl[i] )
		{
			mx = dgr[i] ;
			mnl = lvl[i] ;
			del = i ;
		}
	}
	int ans = mx - 1 ;
	for ( auto el : tree[del] )
	{
		dgr[el]-- ;
	}
	dgr[del] = 0 ;
	int t = 0 ;
	for ( int i = 1 ; i <= n ; i++ )
	{
		t = max ( t , dgr[i] ) ;
	}
	cout << ans + t ;
}

signed main()
{
    NoTLE
    //freopen( "input.txt" , "r" , stdin );
    //freopen( "output.txt" , "w" , stdout );
    int T = 1;
    cin >> T ;
    //int X = T;
    while( T-- )
    {
    	// int ctest = X-T ;
        //noBrainer() ;
        solve();
        cout << nl ;
    }
    return 0;
}

Answer: 2


#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
#ifndef InfernoStinger
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
#define all(x) (x).begin() , (x).end()
#define ll long long
#define int long long
#define mod 1000000007
#define mod1 998244353
#define inf 1e18
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(long double t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(bool t) {cerr << t;}
void _print(unsigned long long t) {cerr << t;}
template <class T> bool ckmin(T&a, const T&b) { bool B = a > b; a = min(a,b); return B; }
template <class T> bool ckmax(T&a, const T&b) { bool B = a < b; a = max(a,b); return B; }
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 << "]";}

int solve()
{
    int n;
    cin>>n;
    vector<set<int>> g(n+1);
    vector<int> deg(n+1, 0);
    multiset<int> curs;
    for(int i=0;i<n-1;i++){
        int v,u;
        cin>>v>>u;
        g[v].insert(u);
        g[u].insert(v);
        deg[u]++;deg[v]++;
    }
    for(int i=1;i<=n;i++){
        curs.insert(deg[i]);
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        int temp=deg[i];
        curs.erase(curs.find(deg[i]));
        for(auto nei:g[i]){
            curs.erase(curs.find(deg[nei]));
            curs.insert(deg[nei]-1);
        }
        ans=max(ans, temp+*curs.rbegin());
        for(auto nei:g[i]){
            curs.erase(curs.find(deg[nei]-1));
            curs.insert(deg[nei]);
        }
        curs.insert(temp);
    }
    cout<<ans-1<<"\n";
    return 0;
}

int32_t main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("Error.txt", "w", stderr);
    #endif
    int t;
    cin>>t;
    for(int tc=0;tc<t;tc++)
    {
        solve();
    }
    return 0;
}

#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
#ifndef InfernoStinger
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
#define all(x) (x).begin() , (x).end()
#define ll long long
#define int long long
#define mod 1000000007
#define mod1 998244353
#define inf 1e18
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(long double t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(bool t) {cerr << t;}
void _print(unsigned long long t) {cerr << t;}
template <class T> bool ckmin(T&a, const T&b) { bool B = a > b; a = min(a,b); return B; }
template <class T> bool ckmax(T&a, const T&b) { bool B = a < b; a = max(a,b); return B; }
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 << "]";}

int solve()
{
    int n;
    cin>>n;
    vector<set<int>> g(n+1);
    vector<int> deg(n+1, 0);
    set<int> cur;
    for(int i=1;i<=n;i++){
        cur.insert(i);
    }
    for(int i=0;i<n-1;i++){
        int v,u;
        cin>>v>>u;
        g[v].insert(u);
        g[u].insert(v);
        deg[u]++;deg[v]++;
    }
    auto red = [&]() -> void {
        int val=0;
        for(auto i:cur){
            if(deg[i]>=deg[val]){
                val=i;
            }
        }
        vector<int> torem;
        for(auto ver:g[val]){
            torem.pb(ver);
        }
        for(auto rem:torem){
            g[rem].erase(val);
            g[val].erase(rem);
            deg[rem]--;deg[val]--;
        }
        cur.erase(val);
    };
    red();
    red();
    queue<int> q;
    vector<bool> vis(n+1, false);
    int ans=0;
    for(auto i:cur){
        if(vis[i]) continue;
        q.push(i);
        ans++;
        while(q.size()){
            int node=q.front();
            q.pop();
            vis[node]=true;
            for(auto ver:g[node]){
                if(!vis[ver]) q.push(ver);
            }
        }
    }
    cout<<ans<<"\n";
    return 0;
}

int32_t main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("Error.txt", "w", stderr);
    #endif
    int t;
    cin>>t;
    for(int tc=0;tc<t;tc++)
    {
        solve();
    }
    return 0;
}

Answer: 1


#include <bits/stdc++.h>
#define FOR(i,j,k) for(int i=j, r##i=k; i<=r##i; ++i)
#define ROF(i,j,k) for(int i=j, l##i=k; i>=l##i; --i)
inline int read (void) {
  int x = 0, f = 1, ch = getchar();
  while(!isdigit(ch)) { if(ch == '-') f = -f; ch = getchar(); }
  while(isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); }
  return x * f;
}
const int maxn = 200005;
int tot_edge, head[maxn], to[maxn<<1], link[maxn<<1];
inline void add_edge (int x, int y) {
  to[++tot_edge] = y;
  link[tot_edge] = head[x];
  head[x] = tot_edge;
}
using pii = std::pair <int, int>;
int d[maxn];
pii p[maxn];
bool flag[maxn];
int main (void) {
  int t = read();
  while(t--) {
    int n = read();
    FOR(i,2,n) {
      int x = read(), y = read();
      add_edge (x, y);
      add_edge (y, x);
      ++ d[x], ++ d[y];
    }
    FOR(i,1,n) p[i] = pii (d[i], i);
    std::sort(p+1, p+n+1, std::greater<pii>());
    int c = -1 << 20, c2 = -1 << 20, uc = -1 << 20;
    for(int now=head[p[1].second]; now; now=link[now])
      flag[to[now]] = 1;
    FOR(i,2,n)
      if(flag[p[i].second])  {
        if(c == -1 << 20) c = p[i].first;
        else if(c2 == -1 << 20) c2 = p[i].first;
      } else
        if(uc == -1 << 20) uc = p[i].first;
    printf("%d\n", std::max (c + c2 - 1, std::max (p[1].first + c - 2, p[1].first + uc - 1)));
    FOR(i,1,n) d[i] = flag[i] = head[i] = 0;
    tot_edge = 0;
  }
  return 0;
}

#include <bits/stdc++.h>
#define FOR(i,j,k) for(int i=j, r##i=k; i<=r##i; ++i)
#define ROF(i,j,k) for(int i=j, l##i=k; i>=l##i; --i)
inline int read (void) {
  int x = 0, f = 1, ch = getchar();
  while(!isdigit(ch)) { if(ch == '-') f = -f; ch = getchar(); }
  while(isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); }
  return x * f;
}
const int maxn = 200005;
int tot_edge, head[maxn], to[maxn], link[maxn];
inline void add_edge (int x, int y) {
  to[++tot_edge] = y;
  link[tot_edge] = head[x];
  head[x] = tot_edge;
}
using pii = std::pair <int, int>;
int d[maxn];
pii p[maxn];
bool flag[maxn];
int main (void) {
  int t = read();
  while(t--) {
    int n = read();
    FOR(i,2,n) {
      int x = read(), y = read();
      add_edge (x, y);
      add_edge (y, x);
      ++ d[x], ++ d[y];
    }
    FOR(i,1,n) p[i] = pii (d[i], i);
    std::sort(p+1, p+n+1, std::greater<pii>());
    int c = -1 << 20, c2 = -1 << 20, uc = -1 << 20;
    for(int now=head[p[1].second]; now; now=link[now])
      flag[to[now]] = 1;
    FOR(i,2,n)
      if(flag[p[i].second])  {
        if(c == -1 << 20) c = p[i].first;
        else if(c2 == -1 << 20) c2 = p[i].first;
      } else
        if(uc == -1 << 20) uc = p[i].first;
    printf("%d\n", std::max (c + c2 - 1, std::max (p[1].first + c - 2, p[1].first + uc - 1)));
    FOR(i,1,n) d[i] = flag[i] = 0;
  }
  return 0;
}

Answer: 1


#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;
void solve(){
	int n;
	cin>>n;
	set<pair<int,int> > s;
	map<int,int> mp;
	vector<pair<int,int> > vc;
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		s.insert({u,v});
		s.insert({v,u});
		mp[u]++;
		mp[v]++;
	}
	for(auto it:mp){
		vc.push_back({it.second,it.first});
	}
	sort(vc.begin(),vc.end());
	int ans=0;
	for(int i=n-1;vc[i].first>=vc[n-1].first&&i>=0;i--){
		for(int j=i-1;vc[j].first>=vc[i-1].first&&j>=0;j--){
			int temp=vc[i].first+vc[j].first;
			//cout<<temp<<endl;
			int u=vc[i].second;
			int v=vc[j].second;
			if(s.find({u,v})==s.end()){   //不相邻
				temp--;
				ans=max(ans,temp);
				cout<<ans<<endl;
				return;
			}else{
				temp-=2;
			}
			ans=max(ans,temp);
		}
	}
	cout<<ans<<endl;
}
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int t;
	cin>>t;
	while(t--){
		solve();
	}
}

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;
void solve(){
	int n;
	cin>>n;
	set<pair<int,int> > s;
	map<int,int> mp;
	vector<pair<int,int> > vc;
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		s.insert({u,v});
		s.insert({v,u});
		mp[u]++;
		mp[v]++;
	}
	for(auto it:mp){
		vc.push_back({it.second,it.first});
	}
	sort(vc.begin(),vc.end());
	int ans=0;
	for(int i=n-1;vc[i].first>=vc[n-1].first&&i>=0;i--){
		for(int j=i-1;vc[j].first>=vc[i-1].first&&j>=0;j--){
			int temp=vc[i].first+vc[j].first;
			//cout<<temp<<endl;
			int u=vc[i].second;
			int v=vc[j].second;
			if(s.find({u,v})==s.end()){   //不相邻
				temp--;
			}else{
				temp-=2;
			}
			ans=max(ans,temp);
		}
	}
	cout<<ans<<endl;
}
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int t;
	cin>>t;
	while(t--){
		solve();
	}
}

Answer: 1


#include <bits/stdc++.h>
using namespace std;
#define F(i, s, e) for(int i = s; i < e; i++)
#define vi vector<int>
#define pb push_back
#define int int_fast64_t
#define sp <<' '<<
#define pii pair<int, int>
#define fi first
#define se second
#define line cout<<"---------------------------------\n";

const int inf = 1e15;
const int N = 2e5+5;
const int mod = 998244353;

vi adj[N];

void solve() {
    int n;
    cin >> n;
    F(i, 0, n) adj[i].clear();
    F(i, 0, n-1) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        adj[u].pb(v);
        adj[v].pb(u);
    }

    multiset<int, greater<int>> cnt;

    F(i, 0, n) cnt.insert(adj[i].size());

    int ans = 0;
    F(i, 0, n) {
        cnt.erase(cnt.find(adj[i].size()));
        for(int nei : adj[i]) cnt.erase(cnt.find(adj[nei].size())), cnt.insert(adj[nei].size() - 1);
        ans = max(ans, (int) adj[i].size() + *cnt.begin() - 1);
        for(int nei : adj[i]) cnt.erase(cnt.find(adj[nei].size() - 1)), cnt.insert(adj[nei].size());
        cnt.insert(adj[i].size());
    }

    cout << ans << endl;
}

int32_t main() {
    #ifdef Local
        freopen("io.in", "r", stdin);
        freopen("io.out", "w", stdout);
    #endif

    int t = 1;
    cin >> t;
    while(t--) solve();
}

#include <bits/stdc++.h>
using namespace std;
#define F(i, s, e) for(int i = s; i < e; i++)
#define int long long
#define vi vector<int>
#define pb push_back
#define sp <<' '<<
#define endl '\n'
#define pii pair<int, int>
#define fi first
#define se second

const int inf = 1e15;
const int N = 1e5 + 5;

vi adj[N];
int dp[N][2][2];
int p[N];

void dfs(int node, int par) {
    p[node] = par;
    int chsize = adj[node].size() - (node != 0);
    dp[node][0][1] = chsize;
    pii best1 = {-inf, -inf}, best2 = {-inf, -inf};
    for(int ch : adj[node]) if(ch != par) {
        dfs(ch, node);
        dp[node][0][0] = max(dp[node][0][0], max(dp[ch][0][0], dp[ch][0][1] + 1));

        dp[node][1][1] = max(dp[node][1][1], chsize - 1 + max(dp[ch][0][0], dp[ch][0][1]));

        pii me = max(pii{dp[ch][0][0], 0}, pii{dp[ch][0][1], 1});
        if(best1.fi < 0) {
            best1 = me;
        } else {
            if(best2.fi < 0) best2 = me;
            else {
                if(me > best2) {
                    best2 = me;
                    if(best2 > best1) swap(best1, best2);
                }
            }
        }
    }
    if(best1.se == 1 && best2.se == 1) {
        dp[node][1][0] = best1.fi + best2.fi + 1;
    } else {
        dp[node][1][0] = best1.fi + best2.fi;
    }
}

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

    F(i, 0, n) adj[i].clear();
    F(i, 0, n) F(j, 0, 2) F(k, 0, 2) dp[i][j][k] = -inf;

    F(i, 0, n-1) {
        int u, v;
        cin >> u >> v;
        u--, v--;
        adj[u].pb(v);
        adj[v].pb(u);
    }

    dfs(0, 0);

    //F(i, 0, n) {
    //    F(j, 0, 2) F(k, 0, 2) cout << dp[i][j][k] << " ";
    //    cout << endl;
    //}

    int ans = max(dp[0][1][0], dp[0][1][1]);

    cout << max(ans, 0ll) << endl;
}

int32_t main() {
    cin.tie(0); ios_base::sync_with_stdio(0);
    #ifdef Local

        freopen("io.in", "r", stdin);
        freopen("io.out", "w", stdout);
    #endif
    int t = 1;
    cin >> t;
    while(t--) solve();
}

Answer: 1