浙江大学计算机与软件学院2021年考研复试上机模拟练习_7-3 preorder traversal-程序员宅基地

技术标签: 算法  c++  图论  

7-1 Square Friends (20 分)

For any given positive integer n, two positive integers A and B are called Square Friends if by attaching 3 digits to every one of the n consecutive numbers starting from A, we can obtain the squares of the n consecutive numbers starting from B.

For example, given n=3, A=73 and B=272 are Square Friends since 73984=272 2, 74529=2732, and 75076=2742.

Now you are asked to find, for any given n, all the Square Friends within the range where A≤MaxA.

Input Specification:
Each input file contains one test case. Each case gives 2 positive integers: n (≤100) and MaxA (≤106), as specified in the problem description.

Output Specification:
Output all the Square Friends within the range where A≤MaxA. Each pair occupies a line in the format A B. If the solution is not unique, print in the non-decreasing order of A; and if there is still a tie, print in the increasing order of B with the same A. Print No Solution. if there is no solution.

Sample Input 1:

3 85

Sample Output 1:

73 272
78 281
82 288
85 293

Sample Input 2:

4 100

Sample Output 2:

No Solution.

这题题意应该有点难读懂吧,参考以下这位大佬的博客解析吧,这里就不过度赘述了。

代码如下:

#include <iostream>
#include <cmath>
using namespace std;

int n, maxA;

bool check(int A, int B)
{
    
    for (int i = 0; i < n; i++)
    {
    
        if (B * B / 1000 != A)
            return false;
        A++;
        B++;
    }
    return true;
}

int main()
{
    
    bool flag = false;
    cin >> n >> maxA;
    for (int i = 1; i <= maxA; i++)
    {
    
        for (int j = sqrt(i * 1000); j <= sqrt((i + 1) * 1000); j++)
        {
    
            if (check(i, j))
            {
    
                flag = true;
                cout << i << " " << j << endl;
            }
        }
    }
    if (flag == false)
        cout << "No Solution." << endl;
    return 0;
}

7-2 One Way In, Two Ways Out (25 分)

Consider a special queue which is a linear structure that allows insertions at one end, yet deletions at both ends. Your job is to check, for a given insertion sequence, if a deletion sequence is possible. For example, if we insert 1, 2, 3, 4, and 5 in order, then it is possible to obtain 1, 3, 2, 5, and 4 as an output, but impossible to obtain 5, 1, 3, 2, and 4.

Input Specification:
Each input file contains one test case. For each case, the first line gives 2 positive integers N and K (≤10), which are the number of insertions and the number of queries, respectively. Then N distinct numbers are given in the next line, as the insertion sequence. Finally K lines follow, each contains N inserted numbers as the deletion sequence to be checked.

All the numbers in a line are separated by spaces.

Output Specification:
For each deletion sequence, print in a line yes if it is indeed possible to be obtained, or no otherwise.

Sample Input:

5 4
10 2 3 4 5
10 3 2 5 4
5 10 3 2 4
2 3 10 4 5
3 5 10 4 2

Sample Output:

yes
no
yes
yes

自己加了一个测试样例方便你进一步测试:
Sample Input:

6 1
10 2 3 4 5 6
3 2 10 4 6 5

Sample Output:

yes

这题一看是双端队列,自己想歪了想了好久,以为是允许两端进一端出,一直不知道怎么写。后面才发现是一端进两端出,相对来说会简单很多,用数组模拟就好了。文末放了个允许两端进一端出的双端队列代码,有兴趣可以看看。

代码如下:

#include <iostream>
#include <queue>
using namespace std;

int main()
{
    
    int n, k, num;
    int deque[100005]; // 模拟双端队列
    queue<int> q;
    cin >> n >> k;
    for (int i = 0; i < n; i++)
    {
    
        cin >> num;
        q.push(num);
    }

    while (k--)
    {
    
        bool flag = true;
        int front = 1, rear = 0;
        queue<int> temp = q;
        for (int i = 0; i < n; i++)
        {
    
            cin >> num;
            while (!temp.empty()) // 这里temp写成q了,死循环不报错找了半天
            {
    
                if (deque[front] == num || deque[rear] == num) // 有可能前面的队列可以出元素符合序列
                    break;
                else // 两边都不满足,那么往双端队列里面插入数据
                {
    
                    int t = temp.front();
                    temp.pop();
                    deque[++rear] = t;
                    if (deque[rear] == num) // 既然前面出不了,只能后面有可能会出元素了
                        break;
                }
            }
            if (deque[front] == num)
                front++;
            else if (deque[rear] == num)
                rear--;
            else
                flag = false; // 不能break,因为必须把元素输入完毕
        }
        if (flag)
            cout << "yes" << endl;
        else
            cout << "no" << endl;
    }
    return 0;
}

7-3 Preorder Traversal (25 分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the last number of the preorder traversal sequence of the corresponding binary tree.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print in one line the last number of the preorder traversal sequence of the corresponding binary tree.

Sample Input:

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

Sample Output:

5

这题比较简单,柳神还专门有文章讲中序后序求前序、中序前序求后序的,如果不太会可以去看一看。

代码如下:

#include <iostream>
using namespace std;

const int MAXN = 50005;
int n, pos = 0;
int pre[MAXN], in[MAXN], post[MAXN];

void getPre(int root, int left, int right)
{
    
    if (left > right)
        return;
    int i = left;
    while (i < right && in[i] != post[root])
        i++;
    pre[pos++] = post[root];
    getPre(root - (right - i + 1), left, i - 1);
    getPre(root - 1, i + 1, right);
}

int main()
{
    
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> post[i];
    for (int i = 0; i < n; i++)
        cin >> in[i];
    getPre(n - 1, 0, n - 1);
    cout << pre[n - 1] << endl;
    return 0;
}

7-4 Load Balancing (30 分)

Load balancing (负载均衡) refers to efficiently distributing incoming network traffic across a group of backend servers. A load balancing algorithm distributes loads in a specific way.

If we can estimate the maximum incoming traffic load, here is an algorithm that works according to the following rule:

  • The incoming traffic load of size S will first be partitioned into two parts, and each part may be again partitioned into two parts, and so on.
  • Only one partition is made at a time.
  • At any time, the size of the smallest load must be strictly greater than half of the size of the largest load.
  • All the sizes are positive integers.
  • This partition process goes on until it is impossible to make any further partition.

For example, if S=7, then we can break it into 3+4 first, then continue as 4=2+2. The process stops at requiring three servers, holding loads 3, 2, and 2.

Your job is to decide the maximum number of backend servers required by this algorithm. Since such kind of partitions may not be unique, find the best solution – that is, the difference between the largest and the smallest sizes is minimized.

Input Specification:
Each input file contains one test case, which gives a positive integer S (2≤N≤200), the size of the incoming traffic load.

Output Specification:
For each case, print two numbers in a line, namely, M, the maximum number of backend servers required, and D, the minimum of the difference between the largest and the smallest sizes in a partition with M servers. The numbers in a line must be separated by one space, and there must be no extra space at the beginning or the end of the line.

Sample Input:

22

Sample Output:

4 1

Hint:
There are more than one way to partition the load. For example:

22
= 8 + 14
= 8 + 7 + 7
= 4 + 4 + 7 + 7

or

22
= 10 + 12
= 10 + 6 + 6
= 4 + 6 + 6 + 6

or

22
= 10 + 12
= 10 + 6 + 6
= 5 + 5 + 6 + 6

All requires 4 servers. The last partition has the smallest difference 6−5=1, hence 1 is printed out.

这道题确实算难的了吧,就看想不想得到DFS了,代码中注释比较详细,理解起来应该问题不大。

代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int maxS = -1, minDiff = 0x3f3f3f3f;
vector<int> arr;

void dfs()
{
    
    bool flag = false;
    sort(arr.begin(), arr.end());
    vector<int> temp = arr; // 备份arr
    int maxLoad = arr[arr.size() - 1];
    for (int i = 1; i <= maxLoad / 2; i++) // 每次都拆解最大的负载(否则会不满足第三个条件)
    {
    
        int load1 = i, load2; // load1、load2分别表示表示按照i、maxLoad-i拆解后的所有负载中的最小的负载、最大的负载
        // 其中数组中任何一个元素都是大于等于maxLoad/2的(条件要求了的),那么拆分之后i就是最小的,因此load1=i,load2就要看拆分后谁最大了
        if (arr.size() >= 2)
            load2 = max(maxLoad - i, arr[arr.size() - 2]);
        else
            load2 = maxLoad - i;

        if (load1 * 2 > load2) // 符合条件则可以继续dfs进行拆分
        {
    
            flag = true;
            arr.pop_back();
            arr.push_back(i);
            arr.push_back(maxLoad - i);
            dfs();
            arr = temp; // dfs返回之后恢复arr原本的数据
        }
    }

    if (flag == false) // 拆解到底了,就看谁分的更多,分的同样多就看谁分出来最大最小负载之差最小
    {
    
        int size = arr.size();
        if (size > maxS)
        {
    
            maxS = size;
            minDiff = arr.back() - arr.front();
        }
        else if (size == maxS)
            minDiff = min(minDiff, arr.back() - arr.front());
    }
}

int main()
{
    
    int s;
    cin >> s;
    arr.push_back(s);
    dfs();
    cout << maxS << " " << minDiff << endl;
    return 0;
}

两端进一端出的双端队列模拟

数据输入方式和7-2模式一样,样例1是自己做的,样例2截取于2022年王道数据结构考研辅导书双端队列部分,如有问题,欢迎指正

Sample Input 1:

5 5
10 2 3 4 5
5 2 10 3 4
5 10 2 4 3
5 2 3 10 4
5 10 2 3 4
10 3 2 4 5

Sample Output 1:

yes
no
no
yes
yes

Sample Input 2:

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

Sample Output 2:

yes
yes
yes
no
no

代码如下:

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main()
{
    
    int n, k, num;
    cin >> n >> k;
    vector<int> rec(10005), temp(10005), deque; // 模拟双端队列,允许两端进一端出
    for (int i = 0; i < n; i++)
        cin >> rec[i];

    while (k--)
    {
    
        int indexRec = 0, indexTemp = 0;
        deque.clear();
        map<int, int> pos;
        for (int i = 0; i < n; i++)
        {
    
            cin >> temp[i];
            pos[temp[i]] = i; // 记录位置
        }

        while (indexRec < n)
        {
    
            if (deque.empty()) // 空的时候就直接往里面插元素就好了
                deque.push_back(rec[indexRec++]);
            else
            {
    
                int curFront = pos[deque[0]];  // 队头在检查序列中的下标
                int next = pos[rec[indexRec]]; // 新元素在检查序列中的下标
                if (next < curFront)
                    deque.insert(deque.begin(), rec[indexRec++]); // 输出序列中在队头左边就放左边
                else
                    deque.push_back(rec[indexRec++]); // 输出序列中在队头右边就放右边
            }

            while (deque.front() == temp[indexTemp])
            {
    
                indexTemp++;
                deque.erase(deque.begin());
            }
        }

        if (indexTemp == n)
            cout << "yes" << endl;
        else
            cout << "no" << endl;
    }
    return 0;
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Slatter/article/details/123513178

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签