Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define fst first
- #define snd second
- #define all(x) (x).begin(), (x).end()
- #define rall(x) (x).rbegin(), (x).rend()
- #define clr(a, v) memset( a , v , sizeof(a) )
- #define pb push_back
- #define mp make_pair
- #define sz size()
- #define FORN( i , s , n ) for( int64 i = (s) ; i < (n) ; i++ )
- #define FOR( i , n ) FORN( i , 0 , n )
- #define FORIT( i , x ) for( typeof x.begin() i = x.begin() ; i != x.end() ; i++ )
- #define trace(x) cout << #x << ": " << x << endl;
- #define trace2(x, y) cout << #x << ": " << x << " | " << #y << ": " << y << endl;
- #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
- #define read ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
- using namespace std;
- typedef long long int64;
- typedef vector <int64> vi;
- typedef pair <int64,int64> ii;
- typedef vector <string> vs;
- typedef vector <ii> vii;
- int N, L; // size of the tree and number of leaves
- vi adj [100005];
- int sze [100005]; // number of leaves in the subtree of i
- int col [100005]; // color assigned to node i
- int maxi[100005]; // maximum number of leaves on a adyacent node of i
- vii V;
- void dfs(int v, int parent, int color){
- sze[v] = 0; // assign 0
- col[v] = color;// assign color
- maxi[v] = 0;
- FOR(i,adj[v].sz) if ( adj[v][i]!=parent ) {
- dfs(adj[v][i],v,color);
- sze[v]+=sze[adj[v][i]]; //refresh number of leaves
- maxi[v] = max (maxi[v],sze[adj[v][i]]); //refresh maxi
- }
- maxi[v] = max(maxi[v], L-sze[v]); // last refresh for the subtree of the parent
- if (adj[v].sz == 1) {
- sze[v]++; // if v is a leaf add 1
- V.pb(ii(col[v],v+1));
- }
- }
- int main(){
- int a,b;
- while(cin>>N){
- FOR(i,N) adj[i].clear();//clean the graph
- FOR(i,N-1) {
- cin>>a>>b;a--;b--; // made the tree 0-index
- adj[a].pb(b);
- adj[b].pb(a);
- }
- if (N==2) {cout<<"1\n1 2\n"; continue;}//special case
- L = 0;
- FOR(i,N) if ( adj[i].sz == 1 ) L++; // number of leaves
- // the arrays sze, col and maxi are not cleared because are assigned in each step
- dfs(0,-1,0);// to find the centroid
- int root = -1;
- FOR(i,N) if (adj[i].sz>1 and maxi[i]<=(L/2) ) root = i; // find the centroid
- int color = 0;
- // assign the color to each neighbord of the root
- V.clear();
- FOR(i,adj[root].sz) dfs( adj[root][i], root, color++ );
- sort(all(V));
- // vector of leaves
- /*FOR(i,N) if ( adj[i].sz == 1 ) V.pb( ii(col[i],i+1) );
- sort(all(V));// sort by color by special cmp
- */
- // if L%2==1 add the first node
- if (V.sz%2 == 1) V.pb( V[0] );
- cout<<V.sz/2<<endl;
- FOR(i, V.sz/2) cout<< V[i].snd <<" "<<V[i+(V.sz/2)].snd<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement