Author: | MathModel |
Prepared by: | MathModel |
Edited by: | MathModel |
A snowflake with parameters has a center of degree , then middle vertices each of degree y+1 (one edge up to , plus edges down to leaves) , and finally leaves of degree . After deleting one edge the graph has m=n-2 edges , and the task is to identify the edge that vanished .
Compute every degree , and for each vertex let be the number of degree- neighbours of . This separates the roles by itself : the center has cnt=0 , since all of its neighbours are middles , while every middle has cnt\ge 1 . So the center is the unique vertex with cnt=0 and degree greater than .
Two cases for the missing edge .
If some vertex has degree , the cut edge was middle-to-leaf and one leaf is now isolated . Every middle still owns leaves except the wounded one , which owns y-1 , so y=(\min_{\text{middles}} cnt)+1 and x=\deg(c) , and the isolated vertex reattaches to the middle achieving that minimum .
Otherwise the cut edge was center-to-middle , detaching one middle together with its leaves . For that detached middle every neighbour is a leaf , so it is the unique with cnt[v]=\deg(v) , and since the center lost a neighbour , x=\deg(c)+1 and y=\max_{v} cnt[v] , the maximum being attained because every middle , attached or not , still keeps its leaves . Add back the edge from the center to that middle , smaller endpoint first .
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int mxn = 2e5 + 5;
int n, m;
int deg[mxn + 1], cnt[mxn + 1];
vector<int>adj[mxn + 1];
void solve(){
cin >> n;
m=n-2;
for(int i = 1; i <= n; i++){ adj[i].clear(); deg[i] = 0; }
for(int i = 1; i <= m; i++){
int u, v; cin >> u >> v;
deg[u]++; deg[v]++;
adj[u].push_back(v); adj[v].push_back(u);
}
for(int i = 1; i <= n; i++)cnt[i] = 0;
int sus = 0;
for(int i = 1; i <= n; i++){
if(deg[i] == 1) cnt[adj[i][0]]++;
else if(deg[i] == 0) sus = i;
}
int x = 0, y = 0, a = 0, b = 0;
if(sus){
int mn = n + 1, id = -1;
for(int i = 1; i <= n; i++) if(cnt[i] && cnt[i] < mn){ mn = cnt[i]; id = i; }
int C = 0;
for(int i = 1; i <= n; i++) if(cnt[i] == 0 && deg[i] > 1) C = i;
x = (int)adj[C].size(); y = mn + 1;
a = id; b = sus;
}else{
int C = 0, mx = 0, id = -1;
for(int i = 1; i <= n; i++){
if(cnt[i] == 0 && deg[i] > 1) C = i;
mx = max(mx, cnt[i]);
}
for(int i = 1; i <= n; i++){
if(cnt[i] == (int)adj[i].size()){ id = i; break; }
}
x = (int)adj[C].size() + 1; y = mx;
a = C; b = id;
}
if(a > b)swap(a, b);
cout << x << " " << y << "\n";
cout << a << " " << b << "\n";
}
int main(){
int tt; cin >> tt;
while(tt--) solve();
}Time complexity: per test case . Memory complexity: .