欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

2019秋季PAT甲级_C++题解

程序员文章站 2022-07-09 20:40:40
2019 秋季 PAT (Advanced Level) C++题解 考试拿到了满分但受考场状态和知识水平所限可能方法不够简洁,此处保留记录,仍需多加学习。备考总结(笔记目录)在 "这里" 7 1 Forever (20 分) "Forever number" is a positive integ ......

2019 秋季 pat (advanced level) c++题解

考试拿到了满分但受考场状态和知识水平所限可能方法不够简洁,此处保留记录,仍需多加学习。备考总结(笔记目录)在

7-1 forever (20 分)

"forever number" is a positive integer a with k digits, satisfying the following constrains:

  • the sum of all the digits of a is m;
  • the sum of all the digits of a+1 is n; and
  • the greatest common divisor of m and n is a prime number which is greater than 2.

now you are supposed to find these forever numbers.

input specification

each input file contains one test case. for each test case, the first line contains a positive integer \(n (≤5)\). then n lines follow, each gives a pair of \(k (3<k<10)\) and \(m (1<m<90)\), of which the meanings are given in the problem description.

output specification

for each pair of k and m, first print in a line case x, where x is the case index (starts from 1). then print n and a in the following line. the numbers must be separated by a space. if the solution is not unique, output in the ascending order of n. if still not unique, output in the ascending order of a. if there is no solution, output no solution.

sample input

2
6 45
7 80

sample output

case 1
10 189999
10 279999
10 369999
10 459999
10 549999
10 639999
10 729999
10 819999
10 909999
case 2
no solution

题目思路

  • 要找到符合要求的数,给出的条件是 数的位数 k 和 各位的和 m
  • 首先要找到满足各位和为 m 的 k 位数,再检查找到的数是否符合要求
  • 用 dfs 找满足各位和为 m 的 k 位数
    • 参数:这个函数内要填写第几位,要填写什么数字,填好后目前所有位的和
    • 由主函数从 1-9 选填第 1 位
    • 进入 dfs 递归过程后,每次填好自己这一位,从 0-9 选填下一位
    • 递归终止条件:填完 k 位后各位之和刚好等于 m,调用函数检查是否符合要求
    • 剪枝
      • 一开始只注意到若要填的位数超过所要求的位数,或目前各位之和已经超过要求的 m 应当停止递归,但这样会运行超时
      • 注意当前几位确定下来时,有很多后面几位比较小的数已经不可能满足各位之和为 m 的条件了,所以每次检查,若 目前各位 + 剩余每位均填 9 都不能达到 m,此枝应当被剪掉
  • 检查找到的数是否符合要求
    • 记忆判断素数和最小公约数函数
    • 每次取到 a 和 a+1,计算好各位之和并求出 gcd,判断是否为素数且 > 2
    • 检查函数返回值为 int,若符合要求返回 a+1 的各位和,若不符合返回 -1 便于调用方进行判断

ac代码

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int k, m;
char s[10];
bool issolved;
struct data{
    int sumn;
    string data;
};
vector<data> result;
bool cmp(data a, data b){ return a.sumn != b.sumn ? a.sumn < b.sumn : a.data < b.data; }
bool isprime(int n){
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++)
        if (n % i == 0) return false;
    return true;
}
int gcd(int a, int b){ return !b ? a : gcd(b,a%b); }
int checkf(){
    int a = stoi(s), b = a+1, suma = 0, sumb = 0;
    string bs = to_string(b);
    for (int i = 0; i < k; i++) suma += s[i]-'0';
    for (int i = 0; i < k; i++) sumb += bs[i]-'0';
    int d = gcd(suma,sumb);
    if (d > 2 && isprime(d)) return sumb;
    else return -1;
}
void dfs(int index, int digit, int sumd){
    if (index > k - 1 || sumd > m) return;
    if (sumd + 9 * (k - index - 1) < m) return;
    s[index] = digit + '0';
    if (sumd == m && index == k - 1){
        if (checkf() >= 0){
            issolved = true;
            string data = s;
            result.push_back({checkf(),data});
        }
        return;
    }
    for (int i = 0; i < 10; i++) dfs(index+1, i, sumd+i);
}

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i < n + 1; i++){
        scanf("%d%d", &k, &m);
        printf("case %d\n", i);
        issolved = false;
        result.clear();
        for (int j = 1; j < 10; j++) dfs(0,j,j);
        if (issolved){
            sort(result.begin(), result.end(), cmp);
            for (int j = 0; j < result.size(); j++)
                cout << result[j].sumn << " " << result[j].data << endl;
        }
        else printf("no solution\n");
    }
    return 0;
}

7-2 merging linked lists (25 分)

given two singly linked lists \(l_1 = a_1 \to a_2 \to ... \to a_{n-1} \to a_n\) and \(l_2 = b_1 \to b_2 \to ... \to b_{m-1} \to b_m\). if \(n≥2m\), you are supposed to reverse and merge the shorter one into the longer one to obtain a list like \(a_1 \to a_2 \to b_m \to a_3 \to a_4 \to b_{m-1} ...\) for example, given one list being 6→7 and the other one 1→2→3→4→5, you must output 1→2→7→3→4→6→5.

input specification

each input file contains one test case. for each case, the first line contains the two addresses of the first nodes of \(l_1\) and \(l_2\) , plus a positive \(n (\le 10^5)\) which is the total number of nodes given. 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:

address data next

where address is the position of the node, data is a positive integer no more than \(10^5\), and next is the position of the next node. it is guaranteed that no list is empty, and the longer list is at least twice as long as the shorter one.

output specification

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

sample input

00100 01000 7
02233 2 34891
00100 6 00001
34891 3 10086
01000 1 02233
00033 5 -1
10086 4 00033
00001 7 -1

sample output

01000 1 02233
02233 2 00001
00001 7 34891
34891 3 10086
10086 4 00100
00100 6 00033
00033 5 -1

题目思路

  • 接收输入链表后,分别遍历两条链,将结点按链表中的顺序存储在容器中
  • 按压入两个长链表的结点就压入一个短链表的结点的顺序将结点压入 result 容器
  • 按要求输出 result 容器中的结点
  • 注意:读题时想当然的以为要将短链表的结点均匀的并入长链表,其实就是题目里的两长一短即可orz

ac代码

#include<iostream>
#include<vector>
using namespace std;
struct node{
    int address, data, next;
} node[100001];
int main()
{
    int head1, head2, n, address, data, next;
    scanf("%d%d%d", &head1, &head2, &n);
    for (int i = 0; i < n; i++){
        scanf("%d%d%d", &address, &data, &next);
        node[address] = {address, data, next};
    }
    vector<node> list1, list2, result;
    for (int p = head1; p != -1; p = node[p].next)
        list1.push_back(node[p]);
    for (int p = head2; p != -1; p = node[p].next)
        list2.push_back(node[p]);
    if (list1.size() > list2.size()){
        int j = list2.size() - 1;
        for (int i = 0; i < list1.size(); i = i + 2){
            result.push_back(list1[i]);
            if (i + 1 < list1.size()) result.push_back(list1[i+1]);
            if (j >= 0) result.push_back(list2[j--]);
        }
    }
    else{
        int j = list1.size() - 1;
        for (int i = 0; i < list2.size(); i = i + 2){
            result.push_back(list2[i]);
            if (i + 1 < list2.size()) result.push_back(list2[i+1]);
            if (j >= 0) result.push_back(list1[j--]);
        }
    }
    for (int i = 0; i + 1 < result.size(); i++)
        printf("%05d %d %05d\n", result[i].address, result[i].data, result[i+1].address);
    printf("%05d %d -1\n", result[result.size()-1].address, result[result.size()-1].data);
    return 0;
}

7-3 postfix expression (25 分)

given a syntax tree (binary), you are supposed to output the corresponding postfix expression, with parentheses reflecting the precedences of the operators.

input specification

each input file contains one test case. for each case, the first line gives a positive integer \(n (≤ 20)\) which is the total number of nodes in the syntax tree. then n lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:

data left_child right_child

where data is a string of no more than 10 characters, left_child and right_child are the indices of this node's left and right children, respectively. the nodes are indexed from 1 to n. the null link is represented by −1. the figures 1 and 2 correspond to the samples 1 and 2, respectively.

2019秋季PAT甲级_C++题解
2019秋季PAT甲级_C++题解

output specification

for each case, print in a line the postfix expression, with parentheses reflecting the precedences of the operators.there must be no space between any symbols.

sample input 1

8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1

sample output 1

(((a)(b)+)((c)(-(d))*)*)

sample input 2

8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1

sample output 2

(((a)(2.35)*)(-((str)(871)%))+)

题目思路

  • 题库 1130 infix expression (25 分)
  • 输入每个结点的左右孩子来建树,用 bool 数组记录结点是否在其他结点的孩子结点中出现过,都没有出现过的即为根结点
  • 在后序遍历基础上要添加括号来表示优先级
  • 一般是每进入一个子树,就用括号将这个子树括起来,然后递归进入左子树和右子树,递归返回后输出根节点内容
  • 注意:表达式中会出现 正负号,此时不能在子结点返回后才输出正负号——特判:当结点左子树为空而右子树不为空时,先输出根节点内容,再进入右子树

ac代码

#include<iostream>
using namespace std;
struct node{
    string data;
    int lchild, rchild;
} node[21];
bool occured[21] = {false};
void postorder(int root){
    cout << "(";
    if (node[root].lchild == -1 && node[root].rchild != -1){
        cout << node[root].data;
        postorder(node[root].rchild);
        cout << ")";
    }
    else{
        if (node[root].lchild != -1) postorder(node[root].lchild);
        if (node[root].rchild != -1) postorder(node[root].rchild);
        cout << node[root].data << ")";
    }
}
int main()
{
    int n, root;
    string data;
    scanf("%d", &n);
    for (int i = 1; i < n + 1; i++){
        cin >> node[i].data >> node[i].lchild >> node[i].rchild;
        if (node[i].lchild != -1) occured[node[i].lchild] = true;
        if (node[i].rchild != -1) occured[node[i].rchild] = true;
    }
    for (root = 1; root < n + 1 && occured[root]; root++);
    postorder(root);
    return 0;
}

7-4 dijkstra sequence (30 分)

dijkstra's algorithm is one of the very famous greedy algorithms. it is used for solving the single source shortest path problem which gives the shortest paths from one particular source vertex to all the other vertices of the given graph. it was conceived by computer scientist edsger w. dijkstra in 1956 and published three years later.

in this algorithm, a set contains vertices included in shortest path tree is maintained. during each step, we find one vertex which is not yet included and has a minimum distance from the source, and collect it into the set. hence step by step an ordered sequence of vertices, let's call it dijkstra sequence, is generated by dijkstra's algorithm.

on the other hand, for a given graph, there could be more than one dijkstra sequence. for example, both { 5, 1, 3, 4, 2 } and { 5, 3, 1, 2, 4 } are dijkstra sequences for the graph, where 5 is the source. your job is to check whether a given sequence is dijkstra sequence or not.

input specification

each input file contains one test case. for each case, the first line contains two positive integers \(n_v(\le 10^3)\) and \(n_e(\le 10^5)\), which are the total numbers of vertices and edges, respectively. hence the vertices are numbered from 1 to \(n_v\)

then \(n_e\) lines follow, each describes an edge by giving the indices of the vertices at the two ends, followed by a positive integer weight (≤100) of the edge. it is guaranteed that the given graph is connected.

finally the number of queries, k, is given as a positive integer no larger than 100, followed by k lines of sequences, each contains a permutationof the \(n_v\) vertices. it is assumed that the first vertex is the source for each sequence.

all the inputs in a line are separated by a space.

output specification

for each of the k sequences, print in a line yes if it is a dijkstra sequence, or no if not.

sample input

5 7
1 2 2
1 5 1
2 3 1
2 4 1
2 5 2
3 5 1
3 4 1
4
5 1 3 4 2
5 3 1 2 4
2 3 4 5 1
3 2 1 5 4

sample output

yes
yes
yes
no

题目思路

  • 注意审题 orz:检查序列是否为 dijkstra 过程中 每次找到 距离原点最近 用于更新相邻点 的 中介点 的 序列
  • dijkstra 每次找目前距原点最近的点,若有几个距离相同的会取其中一个,但其实先检查另外几个点也可
  • 整体模板还是用 dijkstra,每次循环检查 query 的一位
    • 查 当前距离原点最近 的 未访问点 与原点的距离
    • 看 与当前位的 query 中的点 到原点的距离是否符合
    • 若符合,则以 query 当前点为中介 更新邻接点距原点的距离
    • 若不符合,说明此时不应当以 query 当前点为中介继续 dijkstra,即此 query 非所要求的 dijkstra sequence,返回 false

ac代码

#include<iostream>
using namespace std;
const int inf = 0x3fffffff;
int n, g[1001][1001], d[1001], query[1001];
bool dijkstra(int root){
    fill(d, d+1001, inf);
    bool vis[1001] = {false};
    d[root] = 0;
    for (int i = 0; i < n; i++){
        int u, min = inf;
        for (int j = 1; j < n + 1; j++)
            if (d[j] < min && !vis[j])
                min = d[j];
        if (d[query[i]] == min) u = query[i];
        else return false;
        vis[u] = true;
        for (int j = 1; j < n + 1; j++)
            if (g[u][j] && !vis[j] && d[j] > d[u] + g[u][j])
                d[j] = d[u] + g[u][j];
    }
    return true;
}
int main()
{
    int m, u, v, distance, k;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; i++){
        scanf("%d%d%d", &u, &v, &distance);
        g[u][v] = g[v][u] = distance;
    }
    scanf("%d",&k);
    for (int i = 0; i < k; i++){
        for (int j = 0; j < n; j++) scanf("%d", &query[j]);
        bool isd = dijkstra(query[0]);
        printf("%s\n", isd ? "yes" : "no");
    }
    return 0;
}