D. Nastia Plays with a Tree(树形dp)

https://codeforces.com/contest/1521/problem/D


思路:

把树上的单链初始时每个点是一个链。然后类似树形dp递归。递归过程中模拟链的断开,拼凑新的链头链尾。

代码比较清晰

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+1000;
typedef int LL;
typedef pair<LL,LL>P;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL hd[maxn],tl[maxn];
bool vis[maxn];
vector<LL>g[maxn];
vector<P>ans1,ans2;///断边和连边
void dfs(LL u,LL fa){
     for(LL i=0;i<g[u].size();i++){
         LL v=g[u][i];
         if(v==fa) continue;
         dfs(v,u);///搜到底
         if(hd[v]==v){
            if(tl[u]==u){
               tl[u]=tl[v];
               vis[v]=1;
            }
            else if(hd[u]==u){
               hd[u]=tl[v];
               vis[v]=1;
            }
         }
     }
     for(LL i=0;i<g[u].size();i++){
         LL v=g[u][i];
         if(vis[v]||v==fa) continue;
         vis[v]=true;
         ans1.push_back({u,v});
         ans2.push_back({tl[u],hd[v]});
         tl[u]=tl[v];
     }
}
int main(void){
   LL T;T=read();
   while(T--){
      LL n;n=read();
      for(LL i=0;i<=n+10;i++){
          vis[i]=0;g[i].clear();ans1.clear();ans2.clear();
          hd[i]=tl[i]=i;
      }
      for(LL i=1;i<n;i++){
          LL u,v;u=read();v=read();
          g[u].push_back(v);g[v].push_back(u);
      }
      dfs(1,0);///找一个单度数的点当根开始也可以
      printf("%d\n",ans1.size());
      for(LL i=0;i<ans1.size();i++){
          printf("%d %d %d %d\n",ans1[i].first,ans1[i].second,ans2[i].first,ans2[i].second);
      }
   }
   return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值