考虑链的情况,有一个显然的贪心,按左边的的排序,那么最右边的左边时一定选的,依次类推,
把结论推到树上,发现是以LCA的深度来排序的,证明显然,
复杂度: O(nlog(n))
#include
#include
#include
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fod(i,a,b) for(int i=a;i>=b;i--)
#define efo(i,q) for(int i=A[q];i;i=B[i][0])
#define min(q,w) ((q)>(w)?(w):(q))
#define max(q,w) ((q)<(w)?(w):(q))
#define NX(q) ((q)&(-(q)))
using namespace std;
const int N=100500;
int read(int &n)
{
char ch=' ';int q=0,w=1;
for(;(ch!='-')&&((ch<'0')||(ch>'9'));ch=getchar());
if(ch=='-')w=-1,ch=getchar();
for(;ch>='0' && ch<='9';ch=getchar())q=q*10+ch-48;n=q*w;return n;
}
int m,n,ans;
int B[N*2][2],A[N],B0;
int B1[N*3][3],A1[N],B10;
int sum[N],dfn;
int Ans[N];
struct qqww
{
int c,i,si;
int g[20];
}a[N];
void link(int q,int w)
{
B[++B0][0]=A[q],A[q]=B0,B[B0][1]=w;
B[++B0][0]=A[w],A[w]=B0,B[B0][1]=q;
}
void link1(int q,int w,int w1)
{
B1[++B10][0]=A1[q],A1[q]=B10,B1[B10][1]=w,B1[B10][2]=w1;
}
int dfsf(int q,int fa,int c)
{
a[q].c=c;a[q].g[0]=fa;a[q].i=++dfn;
efo(i,q)if(B[i][1]!=fa)a[q].si+=dfsf(B[i][1],q,c+1);
return ++a[q].si;
}
int LCA1(int q,int w)
{
while(a[q].c>w)
{
int i=0;
for(;a[a[q].g[i+1]].c>=w;i++);
q=a[q].g[i];
}
return q;
}
int LCA(int q,int w)
{
q=LCA1(q,a[w].c);w=LCA1(w,a[q].c);
while(q!=w)
{
int i=0;
for(;a[q].g[i+1]!=a[w].g[i+1];i++);
q=a[q].g[i];w=a[w].g[i];
}
return q;
}
int Gsum(int q)
{
int ans=0;
for(;q;q-=NX(q))ans+=sum[q];
return ans;
}
void ADD(int q,int e){for(;q<=n;q+=NX(q))sum[q]+=e;}
void dfs(int q,int fa)
{
efo(i,q)if(B[i][1]!=fa)
{
dfs(B[i][1],q);
}
for(int i=A1[q];i;i=B1[i][0])
{
if(!Gsum(a[B1[i][1]].i)&&!Gsum(a[B1[i][2]].i))
{
Ans[++ans]=q;
ADD(a[q].i,1);
ADD(a[q].i+a[q].si,-1);
break;
}
}
}
int main()
{
freopen("ping.in","r",stdin);
freopen("ping.out","w",stdout);
int q,w,e;
read(n),read(m);
fo(i,1,m)read(q),read(w),link(q,w);
fo(i,1,n)if(!a[i].g[0])dfsf(i,0,1);
fo(j,1,18)fo(i,1,n)a[i].g[j]=a[a[i].g[j-1]].g[j-1];
read(m);
fo(i,1,m)
{
read(q),read(w);
e=LCA(q,w);
if(e)link1(e,q,w);
}
fo(i,1,n)if(!a[i].g[0])dfs(i,0);
printf("%d\n",ans);
fo(i,1,ans)printf("%d ",Ans[i]);
return 0;
}