今天想尝试tarjan,没想到怎么写都爆空间,请大佬帮忙pwp
#include <bits/stdc++.h>
using namespace std;
struct side
{
int dot,next;
}a[1000001];
struct question
{
int dot,next;
}s[1000001];
int z[500001],x[500001],f[500001],n,m,root,ans[500001];
bool vis[500001];
inline int find(int p)
{
if(f[p]==p)
return p;
return f[p]=find(f[p]);
}
void tarjan(int now,int father)
{
int q=z[now];
while(q)
{
tarjan(a[q].dot,now);
q=a[q].next;
}
vis[now]=1;
q=x[now];
while(q)
{
if(vis[s[q].dot]==1)
ans[(q+1)/2]=find(s[q].dot);
q=s[q].next;
}
f[now]=find(father);
return;
}
inline void mema(int q,int w,int top)
{
a[top].dot=w;
a[top].next=z[q];
z[q]=top;
return;
}
inline void mems(int q,int w,int top)
{
s[top].dot=w;
s[top].next=x[q];
x[q]=top;
return;
}
int main()
{
std::ios::sync_with_stdio(0);
cin>>n>>m>>root;
for(int i=1;i<=n;i++)
f[i]=i;
for(int i=1;i<n;i++)
{
int q,w;
cin>>q>>w;
mema(q,w,i*2-1);
mema(w,q,i*2);
}
for(int i=1;i<=m;i++)
{
int q,w;
cin>>q>>w;
mems(q,w,i*2-1);
mems(w,q,i*2);
}
tarjan(root,root);
for(int i=1;i<=m;i++)
cout<<ans[i]<<endl;
return 0;
}