feat(P5022): 添加树遍历算法以处理带删除边的特殊情况

实现新的DFS算法来处理当m≠n-1时需要尝试删除每条边的情况。添加了新的数据结构来存储边信息和比较不同删除方案的结果。当检测到环时,会尝试删除每条边并比较所有可能的遍历顺序,选择字典序最小的方案。
This commit is contained in:
Zengtudor 2025-11-04 11:10:05 +08:00
parent ce9f41f580
commit d4b17f35cc

View File

@ -1,3 +1,4 @@
#include <algorithm>
#include <bitset>
#include <cstdint>
#include <cstdio>
@ -5,26 +6,40 @@
#include <iostream>
#include <istream>
#include <queue>
#include <utility>
#include <vector>
using ll = int64_t;
const ll maxn = 5000+7;
ll n,m;
std::vector<std::priority_queue<ll,std::vector<ll>,std::greater<ll>>> e;
ll n,m,edge[maxn][2],del=-1,sum=0;
std::vector<std::priority_queue<ll,std::vector<ll>,std::greater<ll>>> e,ne;
std::bitset<maxn> b;
std::vector<ll>nans,ans;
#define printf
static inline void dfs(ll f,ll now){
// printf("dfs f=%lld, now=%lld\n",f,now);
std::cout<<now<<" ";
sum++;
printf("dfs f=%lld, now=%lld, sum=%lld\n",f,now,sum);
if(del==-1)std::cout<<now<<" ";
if(del!=-1)nans[sum]=now;
if(del!=-1 && sum==m){
printf("GOT NEW ANS\n");
if(nans<ans){
std::swap(nans,ans);
}
}
while(e[now].size()){
ll top = e[now].top();
// printf("top=%lld\n",top);
e[now].pop();
if(top==f || b[top])continue;
if(del!=-1 && ((edge[del][0]==now&&edge[del][1]==top)||(edge[del][1]==now&&edge[del][0]==top))){
printf("continue now=%lld, top=%lld\n",now,top);
continue;
}
printf("top=%lld\n",top);
if(b[top])continue;
b[top]=true;
dfs(now,top);
}
// printf("---dfs f=%lld, now=%lld\n",f,now);
printf("---dfs f=%lld, now=%lld\n",f,now);
}
int main(){
@ -33,12 +48,34 @@ int main(){
std::cin>>n>>m;
e.resize(n+1);
nans.resize(n+1);
ans.resize(n+1);
b[1]=true;
for(ll i=1;i<=m;i++){
ll u,v;
std::cin>>u>>v;
edge[i][0]=u,edge[i][1]=v;
e[u].push(v);
e[v].push(u);
}
for(ll i=1;i<=m;i++)ans[i]=1e9+7;
ne=e;
if(m==n-1){
dfs(0,1);
}else{
for(ll i=1;i<=m;i++){
printf("BEGIN TREE i=%lld\n",i);
e=ne;
b.reset();
b[1]=true;
del=i;
sum=0;
dfs(0, 1);
}
for(int i=1;i<=n;i++){
std::cout<<ans[i]<<" ";
}
std::cout<<"\n";
}
std::cout<<"\n";
}