您的位置:首页 > 其它

PAT-1133 Splitting A Linked List(链表分解)

2017-09-17 21:52 417 查看
Cutting an integer means to cut a K digits long integer Z into two integers of (K/2) digits long integers A and B. For example, after cutting Z = 167334, we have A = 167 and B = 334. It is interesting to see that Z can be devided
by the product of A and B, as 167334 / (167 x 334) = 3. Given an integer Z, you are supposed to test if it is such an integer.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<= 20). Then N lines follow, each gives an integer Z (10<=Z<=231). It is guaranteed that the number of digits of Z is an even number.

Output Specification:

For each case, print a single line "Yes" if it is such a number, or "No" if not.

Sample Input:
3

167334

2333

12345678

Sample Output:
Yes

No

No

题目大意:这道题形式与之前的乙级题反转链表很相似,给出一条链表以及一个整数k,要求将链表节点分为三部分输出:值小于0,值大于等于0小于等于k,值大于k,并且每部分节点的相对顺序不改变。

主要思路:先定义代表节点的结构体,包含地址(add),值(val),下个地址(next),获取输入并将每个节点存在其地址作为索引的数组中,然后从首节点开始遍历整个链表,如果节点值<0,则直接输出;如果<=k,则存入容器vec1中;如果>k,则存入容器vec2中,然后再依次遍历输出vec1和vec2中的节点。输出的时候注意,在第一次输出的时候只需要输出当前地址和节点值,其余时候需要输出两次地址(前一次作为上一个节点的next)和一次值。

#include <cstdio>
#include <vector>
using namespace std;
typedef struct{
int add;
int val;
int next;
}Node;
Node node[100000];
vector<Node> vec1, vec2;

int main(void) {
int first, n, k, i;
Node x;

scanf("%d%d%d", &first, &n, &k);
for (i = 0; i < n; i++) {
scanf("%d%d%d", &x.add, &x.val, &x.next);
node[x.add] = x;			//节点放入其地址作为索引的数组中
}

//输出小于 0 的部分
bool is_first = true;
for (i = first; i != -1; i = node[i].next) {
if (node[i].val < 0) {
if (is_first) {
printf("%05d %d ", node[i].add, node[i].val);
is_first = false;
}
else
printf("%05d
4000
\n%05d %d ", node[i].add, node[i].add, node[i].val);
}
else if (node[i].val <= k)
vec1.push_back(node[i]);
else
vec2.push_back(node[i]);
}

//输出 [0, k] 的部分
for (i = 0; i < vec1.size(); i++) {
if (is_first) {
printf("05d %d ", vec1[i].add, vec1[i].val);
is_first = false;
}
else
printf("%05d\n%05d %d ", vec1[i].add, vec1[i].add, vec1[i].val);
}

//输出大于 k 的部分
for (i = 0; i < vec2.size(); i++) {
if (is_first) {
printf("%05d %d ", vec2[i].add, vec2[i].val);
is_first = false;
}
else
printf("%05d\n%05d %d ", vec2[i].add, vec2[i].add, vec2[i].val);
}
printf("-1\n");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: