P4665 [BalticOI 2015]Network 题解

题面https://www.luogu.com.cn/problem/P4665

大概就是要把一棵树连一些点使每个点都处在一个环里

显然连叶子节点是比较正确的

然后写好交了一发竟然A了(蓝题也不过如此

代码

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


int tot,n,head[500005],du[500005],f[500005],ff[500005];
struct node{
    int to,nxt;    
}e[1000005];
void add(int u,int v)
{
    tot++;
    e[tot].to=v;
    e[tot].nxt=head[u];
    head[u]=tot;
}

int cnt;

void dfs(int id)
{
    if(du[id]==1)
    {
        cnt++;
        f[cnt]=id;
    }
    for(int i=head[id];i;i=e[i].nxt)
    {
        int v=e[i].to;
        if(v==ff[id]) continue;
        ff[v]=id;
        dfs(v);
    }
}

int main(){
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    cin>>n;
    int x,y;
    for(int i=1;i<=n-1;i++)
    {
        cin>>x>>y;
        add(x,y);
        add(y,x);
        du[x]++;
        du[y]++; 
    }
    for(int i=1;i<=n;i++)
    {
        if(du[i])
        {
            dfs(i);
            break;
        }
    }
    
    cout<<cnt-cnt/2<<endl;
    for(int i=1;i<=cnt/2;i++)
    {
        if(f[i]<f[i+cnt/2]) cout<<f[i]<<" "<<f[i+cnt/2]<<endl;
        else cout<<f[i+cnt/2]<<" "<<f[i]<<endl;
    }
    if(cnt%2==1) cout<<f[cnt/2]<<" "<<f[cnt]<<endl;
    
    return 0;
}

话说这题还可以用random_shuffle做https://53058.blog.luogu.org/solution-p4665

原文地址:https://www.cnblogs.com/Yoicanblog/p/15078936.html