首先,由于 bfs 的性质,是绝对不可能出现一条边连接了两个点在树上的深度之差超过 的。
然后对于连接了两个深度相同的非树边,显然无论怎样给边排序,都不会让它变成树边,所以不用管它。
那么,对于一个连接的点刚好深度之差为 的非树边 ,它一定会造成影响。
具体的, 所在的分支一定是先遍历的,那么意味着,在 和 的分支分离的时候, 的分支是先入队的。那么从 lca 到 分支的这条边肯定优先于从 lca 到 分支这条边。
建立一个新图,原图中每一条边都对应了新图中的一个点。依据上述过程得到的优先条件,可以在新图中建边(如果一条边优先于另一条边,则在新图中建一条由 优先边对应点 指向 次要边对应点 的边。
然后在新图上跑一遍拓扑排序就好了。
Code
#include <bits/stdc++.h>
using namespace std;
int n,m,tot;
vector<int> t[100005];
struct node
{
int u,v,cnt;
bool f;
};//cnt代表输入了几次这个边,f代表是否是树边
map<pair<int,int>,int> mp;
node g[200005];
vector<int> g2[200005];
int fa[100005];
int dep[100005];
int dp[100005][17];
int in[200005];
int top[200005];
void dfs(int x)
{
for(int i = 1;i < 17;i++)
{
dp[x][i] = dp[dp[x][i-1]][i-1];
}
for(auto it:t[x])
{
dep[it] = dep[x]+1;
g[mp[{x,it}]].f = true;
dp[it][0] = x;
dfs(it);
}
return;
}//同时标记树边和预处理倍增
pair<int,pair<int,int> > query(int x,int y)//返回lca和两个分支上的下属点
{
if(dep[x] < dep[y])swap(x,y);
for(int i = 16;i >= 0;i--)
{
if(dep[dp[x][i]] >= dep[y])
{
x = dp[x][i];
}
}
for(int i = 16;i >= 0;i--)
{
if(dp[x][i] != dp[y][i])
{
x = dp[x][i];
y = dp[y][i];
}
}
return {dp[x][0],{x,y}};
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= m;i++)
{
int x,y;
cin >> x >> y;
if(!mp.count({x,y}))
{
tot++;
mp[{x,y}] = mp[{y,x}] = tot;
g[tot] = {x,y,1,0};
}
else
{
g[mp[{x,y}]].cnt++;
}
}
for(int i = 1;i <= n;i++)
{
cin >> fa[i];
t[fa[i]].push_back(i);
}
dfs(0);
for(int i = 1;i <= tot;i++)
{
if(g[i].f)continue;
if(dep[g[i].v] < dep[g[i].u])swap(g[i].u,g[i].v);
if(dep[g[i].v] != dep[g[i].u]+1)continue;
auto res = query(g[i].u,g[i].v);
int lca = res.first;
int sonl = res.second.first;
int sonr = res.second.second;
g2[mp[{lca,sonl}]].push_back(mp[{lca,sonr}]);//建新图的边
in[mp[{lca,sonr}]]++;
}
queue<int> q;
for(int i = 1;i <= tot;i++)
{
if(in[i] == 0)
{
q.push(i);
}
}
int cnt = 0;
while(!q.empty())
{
int t = q.front();
q.pop();
top[++cnt] = t;
for(auto it:g2[t])
{
in[it]--;
if(in[it] == 0)
{
q.push(it);
}
}
}//拓扑排序
for(int i = 1;i <= cnt;i++)
{
int u = g[top[i]].u;
int v = g[top[i]].v;
int cnt2 = g[top[i]].cnt;
while(cnt2--)
{
cout << u << " " << v << "\n";
}
}//输出
return 0;
}