A1166 Block Reversing (25分)

链表

1. 原文

Given a singly linked list L. Let us consider every K nodes as a block (if there are less than K nodes at the end of the list, the rest of the nodes are still considered as a block). Your job is to reverse all the blocks in L. For example, given L as 1→2→3→4→5→6→7→8 and K as 3, your output must be 7→8→4→5→6→1→2→3.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤$10^5$) which is the total number of nodes, and a positive K (≤N) which is the size of a block. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.

Then N lines follow, each describes a node in the format:

1
Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

1
2
3
4
5
6
7
8
9
00100 8 3
71120 7 88666
00000 4 99999
00100 1 12309
68237 6 71120
33218 3 00000
99999 5 68237
88666 8 -1
12309 2 33218

Sample Output:

1
2
3
4
5
6
7
8
71120 7 88666
88666 8 00000
00000 4 99999
99999 5 68237
68237 6 00100
00100 1 12309
12309 2 33218
33218 3 -1

2. 解析思路

按块反向输出链表

vector<int> v[100010];记录每一块,反向输出

3. 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<cstdio>
#include<map>
#include<algorithm>
#include<vector>
using namespace std;
map<int,int> data,nextAdd;
vector<int> v[100010];
int main(){
int first,n,k;
scanf("%d%d%d",&first,&n,&k);
for (int i = 0; i < n; ++i)
{
int a;
scanf("%d",&a);
scanf("%d%d",&data[a],&nextAdd[a]);
}
int cnt = 0;
int idx = 0;
for (int i = first; i != -1; i=nextAdd[i])
{
cnt++;
if (cnt%k!=0)
{
v[idx].push_back(i);
}else{
v[idx].push_back(i);
idx++;
}
}
for (int i = idx; i >= 0; i--)
{
for (int j = 0; j < v[i].size(); ++j)
{
printf("%05d %d ",v[i][j],data[v[i][j]]);
if(j<v[i].size()-1){
printf("%05d\n",v[i][j+1]);
}else{
if(i>0){
printf("%05d\n", v[i-1][0]);
}else{
printf("-1\n");
}
}
}
}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2020/01/20/A1166/
  • 发布时间: 2020-01-20 18:16
  • 更新时间: 2021-10-29 14:12
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!