题目来源:码蹄集
题目描述:
Java代码实现:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static int n, m;
static int[] before = new int[1000005];
static int[] next = new int[1000005];
static boolean[] book = new boolean[1000005];
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
n = Integer.parseInt(line[0]);
m = Integer.parseInt(line[1]);
for(int i = 1; i <= n; i++) {
before[i] = next[i] = i;
}
for(int i = 0; i < m; i++) {
line = br.readLine().split(" ");
int x = Integer.parseInt(line[0]);
int y = Integer.parseInt(line[1]);
next[before[y]] = next[x];
before[next[x]] = before[y];
next[x] = y;
before[y] = x;
}
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= n; i++) {
if(!book[i]) {
int t = i;
do {
sb.append(t + " ");
book[t] = true;
t = next[t];
} while(t != i);
sb.append("\n");
}
}
System.out.print(sb.toString());
}
}
C++代码实现:
参考链接:https://yxsmarter.blog.csdn.net/article/details/128211350?spm=1001.2014.3001.5502
#include<bits/stdc++.h>
using namespace std;
typedef long long int LL;
const int maxn = 1000005;
int n, m;
struct B {
int before, next;
} b[maxn];
bool book[maxn];
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i++)
b[i].before = b[i].next = i;
while(m--) {
int x, y;
cin >> x >> y;
b[b[y].before].next = b[x].next;
b[b[x].next].before = b[y].before;
b[x].next = y;
b[y].before = x;
}
for(int i = 1; i <= n; i++) {
if(!book[i]) {
int t = i;
do {
printf("%d ", t);
book[t] = true;
t = b[t].next;
} while(t != i);
printf("\n");
}
}
return 0;
}
Python代码实现(超内存,错一个测试用例):
class B:
def __init__(self):
self.before = 0
self.next = 0
n, m = map(int, input().split())
b = [B() for _ in range(n+1)]
book = [False] * (n+1)
for i in range(1, n+1):
b[i].before = b[i].next = i
for _ in range(m):
x, y = map(int, input().split())
b[b[y].before].next = b[x].next
b[b[x].next].before = b[y].before
b[x].next = y
b[y].before = x
for i in range(1, n+1):
if not book[i]:
t = i
while True:
print(t, end=" ")
book[t] = True
t = b[t].next
if t == i:
break
print()
代码提交测试结果:
附B站老师思路讲解,可供参考:https://www.bilibili.com/video/BV1Ua4y1V7qX/?t=2939.3