团体程序设计天梯赛 L2-022 重排链表 (25分)

题目链接:

L2-022 重排链表 (25分)

思路:

将原结点编号顺序存下来,然后按规则重排就好;
注意给出的n和实际链表长度并不一样,因为存在无效结点,我们需要自己计算n;

代码:

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1e6 + 5;
int bg, n, dat[maxn], nex[maxn];
void out(vector<int> & v) {
	printf("%05d %d ", v[0], dat[v[0]]);
	for(int i = 1; i < v.size(); ++i) printf("%05d\n%05d %d ", v[i], v[i], dat[v[i]]);
	printf("-1");	
}

int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif	
	scanf("%d %d", &bg, &n);
	for(int i = 0 ; i < n; ++i) {
		int x; scanf("%d", &x);
		scanf("%d %d", &dat[x], &nex[x]);
	}
	vector<int> a, b;
	n = 0;
	for(int now = bg; ~now; now = nex[now])	a.push_back(now), ++n;
	for(int i = 0; i < (n >> 1); ++i) {
		b.push_back(a[n - i - 1]);
		b.push_back(a[i]);
	}
	if(n & 1) b.push_back(a[n / 2]);
	out(b);
	return 0;
}
发布了299 篇原创文章 · 获赞 8 · 访问量 7439

猜你喜欢

转载自blog.csdn.net/qq_45228537/article/details/104071288