1.初见
本来想用二维数组+暴力模拟,然而一看n最大可以到2e5, 时间复杂度O(n^2),遂放弃
2.进一步联想
记得之前在ccf的哪本教程上看到了一道类似的题,大概是用二维数组太大,可以改用邻接表,讲若干个一维数组组成的二维数组“压缩”。于是这题便可以用邻接表解决。
3.关于邻接表
我采用链式前向星的写法。
int head[maxn],cnt;
struct edge //边集数组
{
int to;
int next;
}edge[maxn];
void add(int from, int to) //加边操作
{
edge[++cnt].to=to;
edge[cnt].next=head[from];
head[from]=cnt;
}
每一个栈其实就是一条链,可以定义一个数组,记录每条链的开头,然而考虑到本题的特殊之处,可以再记录一条链的结尾,如下图所示
struct stk
{
int head,tail;
}stk[maxn];
这边有个容易弄混的地方,head[]和stk[].head不是一个东西。head[]是每个节点(元素)所连的最后一条边在edge[]中的编号,而stk[].head是一条链的一个个元素。
完整代码如下。
#include<bits/stdc++.h>
#define FAST ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define INF 0x3f3f3f3f
typedef long long ll;
const int maxn = 3e5+5;
using namespace std;
int n,m,top,cnt;
int head[maxn],temp[maxn];
struct stk
{
int head,tail;
}stk[maxn];
struct edge
{
int to;
int next;
}edge[maxn];
void add(int from, int to)
{
edge[++cnt].to=to;
edge[cnt].next=head[from];
head[from]=cnt;
}
void dfs(int x, int fa) //用dfs遍历每一条链
{
int ans=0;
for (int i=head[x]; i!=-1; i=edge[i].next)
{
if (edge[i].to==fa) continue;
temp[++top]=edge[i].to;
dfs(edge[i].to,x);
}
}
int main()
{
FAST;
while(cin>>n>>m)
{
cnt=0;
memset(stk,-1,sizeof(int)*(n+10));
memset(head,-1,sizeof(int)*(n+10));
memset(edge,-1,sizeof(int)*(n+10));
//此处初始化应该注意,不能直接memset(stk,-1,sizeof(stk)),否则超时,memset的时间复杂度为On
for (int i=1; i<=n; i++) stk[i].head=stk[i].tail=i;
for (int i=1; i<=m; i++)
{
int a,b;
cin>>a>>b;
if (stk[a].head && stk[b].head)
{
add(stk[a].head,stk[b].head);
add(stk[b].head,stk[a].head);
stk[b].head=stk[a].tail;
stk[a].head=stk[a].tail=0;
}
else if (stk[a].head && !stk[b].head)
{
stk[b].tail=stk[a].head;
stk[b].head=stk[a].tail;
stk[a].head=stk[a].tail=0;
}
}
for (int i=1; i<=n; i++)
{
top=0;
if (stk[i].head==0)
{
cout<<0<<endl;
continue;
}
temp[++top]=stk[i].head;
dfs(stk[i].head,0);
cout<<top<<' ';
for (int i=1; i<=top-1; i++) cout<<temp[i]<<' ';
cout<<temp[top];
cout<<endl;
}
}
return 0;
}