PTA作业放在这里

致我亲爱的舍友们:
  以后我就把 PTA 的作业答案放在这了,做完就会写进来(如果没有,要么是我还没做完,要么是我没空,没时间写博客),所以以后要抄的话直接进到 我的博客 ,找到这篇文章,翻到自己想抄的题目后,点击代码块右上角的复制按钮,即可得到代码。
——幻梦的渔人


索引:

1、数据结构

2、C++


数据结构

十三、2024.6.08——数据结构实验(3~6)

数据结构-13

(1)数据结构实验三——简单计算器

数据结构实验三

作者 ZJU

单位 绍兴文理学院

输入一个只包含 + - * / 运算符且运算数都为非负整数的表达式,请计算该表达式的值。

输入格式:

测试数据有多组。对于每组测试,输入一个字符串(长度不超过200)表示的表达式,整数和运算符之间用一个空格分隔。若输入0则输入结束,相应的结果不要输出。测试数据保证没有非法表达式。

输出格式:

对于每组测试,输出表达式的值,结果保留2位小数。

输入样例:

1 + 2
4 + 2 * 5 - 7 / 11
50 - 30 * 2 + 99 / 2 / 2
0

输出样例:

3.00
13.36
14.75

出处:

HDOJ 1237

浙大计算机研究生复试上机考试-2006年

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <iostream>
#include<stack>
using namespace std;
int main(){
stack<double> st;
double num1;
char ch;
while(scanf("%lf",&num1)!=EOF)
{
// num1检查是否结束
ch=getchar();
if(num1==0&&ch!=' '){
break;
}
st.push(num1);// 压入栈
double num;
char exp,space;
while(scanf("%c %lf%c",&exp,&num,&space))
{
switch(exp)
{
case'+':
st.push(num);// 正的直接压入
break;
case'-':
st.push(-1*num);// 负的也是,*-1
break;
case'*':
st.top()*=num;// 当前顶点*num
break;
case'/':
st.top()/=num;// 当前顶点/num
break;
}
if(space=='\n')
break;
}
double sum=0;
while(!st.empty()){
sum+=st.top();
st.pop();
}
printf("%.2f\n",sum);
}
return 0;
}

(2)数据结构实验四——哈夫曼编码

数据结构实验四

作者 张瑞霞

单位 桂林电子科技大学

本题要求字符的哈夫曼编码,注意建立的哈夫曼树严格按照左小右次小的顺序,并且哈夫曼编码时严格按照左‘0’右‘1’进行编码。

输入格式:

输入是各个字符在通信中出现的频率

输出格式:

输出是各个字符的哈夫曼编码,每个字母占一行

输入样例:

A:2
B:3
C:6
D:7
E:10
F:19
G:21
H:32

输出样例:

A:10000
B:10001
C:1001
D:1010
E:1011
F:00
G:01
H:11

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INITIAL_SIZE 10

typedef struct {
double weight;
char s;
int parent, lchild, rchild;
} Htnode, *htree;

void select(htree ht, int x, int *m1, int *m2);
void creath(htree ht, int n);
void hcode(htree ht, char **hc, int n);
void printh_sorted(htree ht, char **hc, int n);

int main() {
int size = INITIAL_SIZE;
htree ht = (htree)malloc((2 * size - 1) * sizeof(Htnode));
int n = 0;
char line[100];
char *hc[2 * size];

while (fgets(line, sizeof(line), stdin)) {
if (n == size) {
size *= 2;
ht = (htree)realloc(ht, (2 * size - 1) * sizeof(Htnode));
}

sscanf(line, "%c:%lf", &ht[n + 1].s, &ht[n + 1].weight);
ht[n + 1].lchild = 0;
ht[n + 1].rchild = 0;
ht[n + 1].parent = 0;
n++;
}

creath(ht, n);
hcode(ht, hc, n);
printh_sorted(ht, hc, n);

for (int i = 1; i <= n; i++) {
free(hc[i]);
}
free(ht);

return 0;
}

void select(htree ht, int x, int *m1, int *m2) {
double min1 = 99999;
double min2 = 99999;
int j;
for (j = 1; j <= x; j++) {
if (ht[j].weight < min1 && ht[j].parent == 0) {
min1 = ht[j].weight;
*m1 = j;
}
}
int k;
for (k = 1; k <= x; k++) {
if (ht[k].weight < min2 && k != *m1 && ht[k].parent == 0) {
min2 = ht[k].weight;
*m2 = k;
}
}
}

void creath(htree ht, int n) {
int i;
for (i = n + 1; i <= 2 * n - 1; i++) {
int m1, m2;
select(ht, i - 1, &m1, &m2);
ht[i].weight = ht[m1].weight + ht[m2].weight;
ht[i].lchild = m1;
ht[i].rchild = m2;
ht[m1].parent = i;
ht[m2].parent = i;
}
}

void hcode(htree ht, char **hc, int n) {
char *cd = (char *)malloc(n * sizeof(char));
cd[n - 1] = '\0';
int now = 1;
int p = 0;
int start;
int i = 0;
while (i < n) {
start = n - 1;
now = i + 1;
p = ht[now].parent;
while (p != 0) {
start--;
if (ht[p].lchild == now) {
cd[start] = '0';
} else {
cd[start] = '1';
}
now = p;
p = ht[now].parent;
}
hc[i + 1] = (char *)malloc((n - start) * sizeof(char));
strcpy(hc[i + 1], &cd[start]);
i++;
}
free(cd);
}

void printh_sorted(htree ht, char **hc, int n) {
typedef struct {
char s;
char *code;
} SymbolCode;

SymbolCode symbols[n];
for (int i = 1; i <= n; i++) {
symbols[i - 1].s = ht[i].s;
symbols[i - 1].code = hc[i];
}

qsort(symbols, n, sizeof(SymbolCode), [](const void *a, const void *b) {
return ((SymbolCode *)a)->s - ((SymbolCode *)b)->s;
});

for (int i = 0; i < n; i++) {
printf("%c:%s\n", symbols[i].s, symbols[i].code);
}
}

(3)数据结构实验五—— 双十一

数据结构实验五

作者 朱允刚

单位 吉林大学

双十一期间,某著名电商平台“东东”为应对销售高峰,准备在n个城市中再增加一个自营仓库,其要求是该仓库设在n个城市中的某个城市,且距离其他所有城市的最短距离之和最小。请编写程序帮助“东东”找出设立仓库的地点。假定n个城市编号为0至n-1,它们之间至少有一个城市与其他所有城市可及。

输入格式:

输入包含多组数据。每组数据第一行为两个正整数n和e,均不超过100。n表示城市数。接下来e行表示两个城市间的距离信息,每行为3个非负整数a、b、c,其中a和b表示两个城市编号,c表示城市间的距离。

提示:可使用EOF判断输入结束。

输出格式:

输出为一个整数,表示建立仓库的城市编号,如多个城市满足要求,则输出编号最小者。

输入样例:

6 5
0 1 1
0 2 1
0 3 1
0 4 1
0 5 1
4 5
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1

输出样例:

0
1

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
int n,e,i,j,k,a[150][150],x,y,v;
while(scanf("%d %d",&n,&e)!=EOF){
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=0x3f7f7f7f;
for(i=0;i<e;i++){
scanf("%d %d %d",&x,&y,&v);
a[x][y]=v;
a[y][x]=v;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(a[i][k]+a[k][j]<a[i][j])
a[i][j]=a[i][k]+a[k][j];
int s[150];
for(i=0;i<n;i++)
s[i]=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(i!=j)s[i]+=a[i][j];
int min=0;
for(i=1;i<n;i++)
if(s[i]<s[min])min=i;
printf("%d\n",min);
}

return 0;
}

(4)数据结构实验六—— 六度空间

数据结构实验六

作者 DS课程组

单位 浙江大学

“六度空间”理论又称作“六度分隔(Six Degrees of Separation)”理论。这个理论可以通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过五个人你就能够认识任何一个陌生人。”如图1所示。

“六度空间”理论虽然得到广泛的认同,并且正在得到越来越多的应用。但是数十年来,试图验证这个理论始终是许多社会学家努力追求的目标。然而由于历史的原因,这样的研究具有太大的局限性和困难。随着当代人的联络主要依赖于电话、短信、微信以及因特网上即时通信等工具,能够体现社交网络关系的一手数据已经逐渐使得“六度空间”理论的验证成为可能。

假如给你一个社交网络图,请你对每个节点计算符合“六度空间”理论的结点占结点总数的百分比。

输入格式:

输入第1行给出两个正整数,分别表示社交网络图的结点数N(1<N≤103,表示人数)、边数M(≤33×N,表示社交关系数)。随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个结点的编号(节点从1到N编号)。

输出格式:

对每个结点输出与该结点距离不超过6的结点数占结点总数的百分比,精确到小数点后2位。每个结节点输出一行,格式为“结点编号:(空格)百分比%”。

输入样例:

10 9
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

输出样例:

1: 70.00%
2: 80.00%
3: 90.00%
4: 100.00%
5: 100.00%
6: 100.00%
7: 100.00%
8: 90.00%
9: 80.00%
10: 70.00%

代码长度限制:16 KB

时间限制:500 ms

内存限制:64 MB

答案:

#include<iostream>
#include<queue>
using namespace std;
int g[10001][10001],v,e,x,y,i;
int bfs(int z)
{
int i,vis[10001]={0},last=z,tail,level=0,count=1;
queue<int>q;
q.push(z);
vis[z]=1;
while(!q.empty())
{
z=q.front();
q.pop();
for(i=1;i<=v;i++)
{
if(g[z][i]==1 && vis[i]==0)
{
count++;
vis[i]=1;
q.push(i);
tail=i;
}
}
if(last==z)
{
level++;
last=tail;
}
if(level==6) break;
}
return count;
}
int main()
{
cin>>v>>e;
while(e--)
{
cin>>x>>y;
g[x][y]=g[y][x]=1;
}
for(i=1;i<=v;i++)
{
double n=v;
double m=bfs(i);
printf("%d: %.2f%%\n",i,m/n*100);
}
return 0;
}

十二、2024.6.02——排序作业2

数据结构-12

(1)编程题

数据结构-12.1

7-1 老板的作息表

数据结构-7-1

作者 陈越

单位 浙江大学

zcy.png

新浪微博上有人发了某老板的作息时间表,表示其每天 4:30 就起床了。但立刻有眼尖的网友问:这时间表不完整啊,早上九点到下午一点干啥了?

本题就请你编写程序,检查任意一张时间表,找出其中没写出来的时间段。

输入格式:

输入第一行给出一个正整数 N,为作息表上列出的时间段的个数。随后 N 行,每行给出一个时间段,格式为:
hh:mm:ss - hh:mm:ss

其中 hh、mm、ss 分别是两位数表示的小时、分钟、秒。第一个时间是开始时间,第二个是结束时间。题目保证所有时间都在一天之内(即从 00:00:00 到 23:59:59);每个区间间隔至少 1 秒;并且任意两个给出的时间区间最多只在一个端点有重合,没有区间重叠的情况。

输出格式:

按照时间顺序列出时间表中没有出现的区间,每个区间占一行,格式与输入相同。题目保证至少存在一个区间需要输出。

输入样例:

8
13:00:00 - 18:00:00
00:00:00 - 01:00:05
08:00:00 - 09:00:00
07:10:59 - 08:00:00
01:00:05 - 04:30:00
06:30:00 - 07:10:58
05:30:00 - 06:30:00
18:00:00 - 19:00:00

输出样例:

04:30:00 - 05:30:00
07:10:58 - 07:10:59
09:00:00 - 13:00:00
19:00:00 - 23:59:59

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自天梯赛真题——7-6 老板的作息表(25 分)-阿里云开发者社区 (aliyun.com))

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

struct Time
{
string first;
string last;
};

bool Mysort(Time& a, Time& b) {
return a.first < b.first;
}

int main()
{
int n;
cin >> n;
string a, b;
vector<Time>v, result;
char c;
for (int i = 0; i < n; i++) {
Time t;
cin >> a >> c >> b;
for (int i = 0; i < a.size(); i++) {
if (isalnum(a[i]))
t.first += a[i];
}
for (int i = 0; i < b.size(); i++) {
if (isalnum(b[i]))
t.last += b[i];
}
v.push_back(t);
}
sort(v.begin(), v.end(), Mysort);
Time t;
if (v[0].first != "000000") {
t.first = "000000";
t.last = v[0].first;
result.push_back(t);
}
for (int i = 0; i < n - 1; i++) {
//如果重合则跳过
if (v[i].last == v[i + 1].first)
continue;
//没有的话找出中间区间
else {
t.first = v[i].last;
t.last = v[i + 1].first;
result.push_back(t);
}
}
if (v[n - 1].last != "235959") {
t.first = v[n - 1].last;
t.last = "235959";
result.push_back(t);
}
//输出
for (int i = 0; i < result.size(); i++) {
cout << result[i].first[0] << result[i].first[1] << ":" << result[i].first[2] << result[i].first[3] << ":" << result[i].first[4] << result[i].first[5];
cout << " - ";
cout << result[i].last[0] << result[i].last[1] << ":" << result[i].last[2] << result[i].last[3] << ":" << result[i].last[4] << result[i].last[5] << endl;
}
return 0;
}

7-2 统计工龄

数据结构-7-2

作者 陈越

单位 浙江大学

给定公司N名员工的工龄,要求按工龄增序输出每个工龄段有多少员工。

输入格式:

输入首先给出正整数N(≤105),即员工总人数;随后给出N个整数,即每个员工的工龄,范围在[0, 50]。

输出格式:

按工龄的递增顺序输出每个工龄的员工个数,格式为:“工龄:人数”。每项占一行。如果人数为0则不输出该项。

输入样例:

8
10 2 0 5 7 2 5 2

输出样例:

0:1
2:3
5:2
7:1
10:1

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

答案:

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int i,n;
cin>>n;
int a[100000]={0},t,max=0;
getchar();
for(i=0;i<n;i++)
{
cin>>t;
max=t>max?t:max;
a[t]++;
}
for(i=0;i<=max;i++)
{
if(a[i]!=0)
cout<<i<<":"<<a[i]<<endl;
}
return 0;
}

7-3 PAT排名汇总

数据结构-7-3

作者 陈越

单位 浙江大学

计算机程序设计能力考试(Programming Ability Test,简称PAT)旨在通过统一组织的在线考试及自动评测方法客观地评判考生的算法设计与程序设计实现能力,科学的评价计算机程序设计人才,为企业选拔人才提供参考标准(网址http://www.patest.cn)。

每次考试会在若干个不同的考点同时举行,每个考点用局域网,产生本考点的成绩。考试结束后,各个考点的成绩将即刻汇总成一张总的排名表。

现在就请你写一个程序自动归并各个考点的成绩并生成总排名表。

输入格式:

输入的第一行给出一个正整数N(≤100),代表考点总数。随后给出N个考点的成绩,格式为:首先一行给出正整数K(≤300),代表该考点的考生总数;随后K行,每行给出1个考生的信息,包括考号(由13位整数字组成)和得分(为[0,100]区间内的整数),中间用空格分隔。

输出格式:

首先在第一行里输出考生总数。随后输出汇总的排名表,每个考生的信息占一行,顺序为:考号、最终排名、考点编号、在该考点的排名。其中考点按输入给出的顺序从1到N编号。考生的输出须按最终排名的非递减顺序输出,获得相同分数的考生应有相同名次,并按考号的递增顺序输出。

输入样例:

2
5
1234567890001 95
1234567890005 100
1234567890003 95
1234567890002 77
1234567890004 85
4
1234567890013 65
1234567890011 25
1234567890014 100
1234567890012 85

输出样例:

9
1234567890005 1 1 1
1234567890014 1 2 1
1234567890001 3 1 2
1234567890003 3 1 2
1234567890004 5 1 4
1234567890012 5 2 2
1234567890002 7 1 5
1234567890013 8 2 3
1234567890011 9 2 4

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-3 PAT排名汇总 (25 分) - 代码先锋网 (codeleading.com))

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
struct PNode
{
string kh;
int grade;
int zzpm;
int kdpm;
int kdcode;
};
bool comb(PNode a, PNode b)
{
if (a.grade != b.grade)
return a.grade > b.grade;
else
return a.kh < b.kh;
}
int main()
{
vector<PNode>zpm;
int sc = 0;
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
int temp;
cin >> temp;
sc += temp;
vector<PNode>kc(temp);
for (int j = 0; j < temp; j++)
{
cin >> kc[j].kh;
cin >> kc[j].grade;
kc[j].kdcode = i;
}
sort(kc.begin(), kc.end(), comb);
kc[0].kdpm = 1;
for (int j = 1; j < temp; j++)
{
if (kc[j].grade != kc[j - 1].grade)
kc[j].kdpm = j + 1;
else
kc[j].kdpm = kc[j - 1].kdpm;
}
zpm.insert(zpm.end(), kc.begin(), kc.end());
}
sort(zpm.begin(), zpm.end(), comb);
zpm[0].zzpm = 1;
for (int i = 1; i < zpm.size(); i++)
{
if (zpm[i].grade != zpm[i - 1].grade)
zpm[i].zzpm = i + 1;
else
zpm[i].zzpm = zpm[i - 1].zzpm;
}
cout << sc << endl;
for (int i = 0; i < zpm.size(); i++)
cout << zpm[i].kh << " " << zpm[i].zzpm << " " << zpm[i].kdcode << " " << zpm[i].kdpm << endl;
return 0;
}

7-4 寻找大富翁

数据结构-7-4

作者 陈越

单位 浙江大学

胡润研究院的调查显示,截至2017年底,中国个人资产超过1亿元的高净值人群达15万人。假设给出N个人的个人资产值,请快速找出资产排前M位的大富翁。

输入格式:

输入首先给出两个正整数N(≤106)和M(≤10),其中N为总人数,M为需要找出的大富翁数;接下来一行给出N个人的个人资产值,以百万元为单位,为不超过长整型范围的整数。数字间以空格分隔。

输出格式:

在一行内按非递增顺序输出资产排前M位的大富翁的个人资产值。数字间以空格分隔,但结尾不得有多余空格。

输入样例:

8 3
8 12 7 3 20 9 5 18

输出样例:

20 18 12

代码长度限制:16 KB

时间限制:500 ms

内存限制:64 MB

答案:

#include<iostream>
#include<algorithm>
using namespace std;
bool complare(int x,int y)
{return x>y;}
int main() {
long long i,n,m;
cin>>n>>m;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n,complare);
cout<<a[0];
m=m<n?m:n;
for(i=1;i<m;i++)
cout<<" "<<a[i];
return 0;
}

十一、2024.5.25——排序作业1

数据结构-11

(1)编程题

数据结构-11.1

7-1 字符串的冒泡排序

数据结构-7-1

作者 陈越

单位 浙江大学

我们已经知道了将N个整数按从小到大排序的冒泡排序法。本题要求将此方法用于字符串序列,并对任意给定的K(<N),输出扫描完第K遍后的中间结果序列。

输入格式:

输入在第1行中给出N和K(1≤K<N≤100),此后N行,每行包含一个长度不超过10的、仅由小写英文字母组成的非空字符串。

输出格式:

输出冒泡排序法扫描完第K遍后的中间结果序列,每行包含一个字符串。

输入样例:

6 2
best
cat
east
a
free
day

输出样例:

best
a
cat
day
east
free

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include <stdio.h>
#include <stdlib.h>

int main() {
char s[1000][100];
int n,m,i,j;
scanf("%d %d",&n,&m);
getchar();
for(i=0;i<n;i++)
{
gets(s[i]);
}
for(i=n-1;i>n-m-1;i--)
{
for(j=0;j<i;j++)
{
if(strcmp(s[j],s[j+1])>0)
{
char t[100];
strcpy(t,s[j]);
strcpy(s[j],s[j+1]);
strcpy(s[j+1],t);
}
}
}
for(i=0;i<n;i++)
puts(s[i]);
return 0;
}

7-2 插入排序还是归并排序

数据结构-7-2

作者 陈越

单位 浙江大学

根据维基百科的定义:

插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列。每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置。如此迭代直到全部元素有序。

归并排序进行如下迭代操作:首先将原始序列看成 N 个只包含 1 个元素的有序子序列,然后每次迭代归并两个相邻的有序子序列,直到最后只剩下 1 个有序的序列。

现给定原始序列和由某排序算法产生的中间序列,请你判断该算法究竟是哪种排序算法?

输入格式:

输入在第一行给出正整数 N (≤100);随后一行给出原始序列的 N 个整数;最后一行给出由某排序算法产生的中间序列。这里假设排序的目标序列是升序。数字间以空格分隔。

输出格式:

首先在第 1 行中输出Insertion Sort表示插入排序、或Merge Sort表示归并排序;然后在第 2 行中输出用该排序算法再迭代一轮的结果序列。题目保证每组测试的结果是唯一的。数字间以空格分隔,且行首尾不得有多余空格。

输入样例 1:

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0

输出样例 1:

Insertion Sort
1 2 3 5 7 8 9 4 6 0

输入样例 2:

10
3 1 2 8 7 5 9 4 0 6
1 3 2 8 5 7 4 9 0 6

输出样例 2:

Merge Sort
1 2 3 8 4 5 7 9 0 6**

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

答案:(引用自数据结构PTA7.1.2 插入排序还是归并排序?(两种解法)_pta7-1插入排序还是堆排序-CSDN博客)

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>


void Swap(int *a, int *b)
{
int tmp = *a; *a = *b; *b = tmp;
}

bool IsEqual(int *P, int *PMid, int N)
{
for(int i=0; i<N; i++)
{
if(P[i] != PMid[i])
return false;
}
return true;
}

void PrintResult(int *P, int N)
{
for(int i=0; i<N; i++)
{
if(i==0)
printf("%d", P[i]);
if(i!=0)
printf(" %d", P[i]);
}
}

int InsertSortTest(int *P, int *PMid, int N)
{
int i,j;
int flag = 0;
for(i=1; i<N; i++)
{
int tmp = P[i];
for(j=i-1; j>=0; j--)
{
P[j+1] = P[j];
if(P[j]<=tmp)
break;
}
Swap(&P[j+1], &tmp);
if(IsEqual(P, PMid, N))
{
printf("Insertion Sort\n");
flag = 1;
continue;
}
if(flag==1)
{
PrintResult(P, N);
return 1;
}

}
return 0;
}

void Merge(int *P, int *tmpP, int L, int R, int RightEnd)
{
int LeftEnd = R-1;
int tmp = L;
int ElementN = RightEnd-L+1;
while(L<=LeftEnd && R<=RightEnd)
{
if(P[L]>P[R])
tmpP[tmp++] = P[R++];
else
tmpP[tmp++] = P[L++];
}
while(L<=LeftEnd) tmpP[tmp++] = P[L++];
while(R<=RightEnd) tmpP[tmp++] = P[R++]; //build the whole tmp[]

for(int i=0; i<ElementN; i++,RightEnd--) //copy to P[]
P[RightEnd] = tmpP[RightEnd];
}

void Merge_pass(int A[], int TmpA[], int N, int length )
{
int i, j;

for ( i=0; i <= N-2*length; i += 2*length )
Merge( A, TmpA, i, i+length, i+2*length-1 );
if ( i+length < N )
Merge( A, TmpA, i, i+length, N-1);
else
for ( j = i; j < N; j++ )
TmpA[j] = A[j];
}

int MergeSortTest(int A[], int *PMid, int N )
{
int length;
int *TmpA;
int flag = 0;
length = 1;
TmpA = malloc( N * sizeof( int) );
if ( TmpA != NULL ) {
while( length < N ) {
Merge_pass( A, TmpA, N, length );
length *= 2;
if(IsEqual(A, PMid, N))
{
printf("Merge Sort\n");
flag = 1;
continue;
}
if(flag==1)
{
PrintResult(A, N);
return 1;
}
}
free( TmpA );
}
return 0;
}

int main()
{
int N;
scanf("%d", &N);
int *P1 = (int *)malloc(N*sizeof(int));
int *P2 = (int *)malloc(N*sizeof(int));
int *PMid = (int *)malloc(N*sizeof(int));
for(int i=0; i<N; i++)
{
scanf("%d", &P1[i]);
}
for(int i=0; i<N; i++)
P2[i] = P1[i];
for(int i=0; i<N; i++)
{
scanf("%d", &PMid[i]);
}

if(!InsertSortTest(P1, PMid, N))
MergeSortTest(P2, PMid, N);

free(P1);
free(P2);
free(PMid);

return 0;
}


7-3 插入排序还是堆排序

数据结构-7-3

作者 周强

单位 青岛大学

根据维基百科的定义:

插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列。每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置。如此迭代直到全部元素有序。

堆排序也是将输入分为有序和无序两部分,迭代地从无序部分找出最大元素放入有序部分。它利用了大根堆的堆顶元素最大这一特征,使得在当前无序区中选取最大元素变得简单。

现给定原始序列和由某排序算法产生的中间序列,请你判断该算法究竟是哪种排序算法?

输入格式:

输入在第一行给出正整数 N (≤100);随后一行给出原始序列的 N 个整数;最后一行给出由某排序算法产生的中间序列。这里假设排序的目标序列是升序。数字间以空格分隔。

输出格式:

首先在第 1 行中输出Insertion Sort表示插入排序、或Heap Sort表示堆排序;然后在第 2 行中输出用该排序算法再迭代一轮的结果序列。题目保证每组测试的结果是唯一的。数字间以空格分隔,且行首尾不得有多余空格。

输入样例 1:

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0

输出样例 1:

Insertion Sort
1 2 3 5 7 8 9 4 6 0

输入样例 2:

10
3 1 2 8 7 5 9 4 6 0
6 4 5 1 0 3 2 7 8 9

输出样例 2:

Heap Sort
5 4 3 1 0 2 6 7 8 9

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自数据结构PTA 基础实验7-2.2 插入排序还是堆排序_pta堆排序-CSDN博客)

#include<stdio.h>
#include<stdlib.h>

void Swap(int *a, int *b)
{
int tmp = *a; *a = *b; *b = tmp;
}

void InsertionSortOneStep(int *P, int i, int N)
{
int j;
int tmp = P[i];
for(j=i; j>0; j--)
{
if(tmp<P[j-1])
P[j] = P[j-1];
else
break;
}
P[j] = tmp;
}

void ScanNumber(int *P, int N)
{
for(int i=0; i<N; i++)
scanf("%d", &P[i]);
}

void CopyArr(int *P1, int *P2, int N)
{
for(int i=0; i<N; i++)
P2[i] = P1[i];
}

int IsEqual(int *P, int *P1, int N)
{
for(int i=0; i<N; i++)
{
if(P[i]!=P1[i])
return 0;
}
return 1;
}

void ShowResult(int *P ,int N)
{
printf("%d", P[0]);
for(int i=1; i<N; i++)
printf(" %d", P[i]);
}

void BuildHeap(int *P, int N)
{
for(int i=(N-1)/2; i>=0; i--)
PerDown(P, i, N);
}

void PerDown(int *P, int i, int N)
{
int Child;
int tmp = P[i];
for(; 2*i+1<N; i=Child)
{
Child = 2*i+1;
if(P[Child]<P[Child+1] && Child!=N-1)
Child++;
if(tmp<P[Child])
P[i] = P[Child];
else
break;
}
P[i] = tmp;
}

//void HeapSortOneStep(int *P, int N);


int main()
{

int N;
scanf("%d", &N);
int *P1 = (int *)malloc(N*sizeof(int));
int *P2 = (int *)malloc(N*sizeof(int));
ScanNumber(P1, N);
CopyArr(P1, P2, N);

int *CP = (int *)malloc(N*sizeof(int));
ScanNumber(CP, N);


//InsertionSort Test
int i;
int flag = 0;
for(i=1; i<N; i++)
{
InsertionSortOneStep(P1, i, N);
if(IsEqual(P1, CP, N))
{
flag = 1;
break;
}

}

if(flag == 1)
{
printf("Insertion Sort\n");
InsertionSortOneStep(P1, i+1, N);
ShowResult(P1 ,N);
}
else
{
BuildHeap(P2, N);
for(i=N-1; i>0; i--)
{
Swap(&P2[i], &P2[0]);
PerDown(P2, 0, i);
if(IsEqual(P2, CP, N))
{
printf("Heap Sort\n");
Swap(&P2[i-1], &P2[0]);
PerDown(P2, 0, i-1);
ShowResult(P2 ,N);
break;
}
}
}


return 0;
}



7-4 排序

数据结构-7-4

作者 陈越

单位 浙江大学

给定N个(长整型范围内的)整数,要求输出从小到大排序后的结果。

本题旨在测试各种不同的排序算法在各种数据情况下的表现。各组测试数据特点如下:

  • 数据1:只有1个元素;

  • 数据2:11个不相同的整数,测试基本正确性;

  • 数据3:103个随机整数;

  • 数据4:104个随机整数;

  • 数据5:105个随机整数;

  • 数据6:105个顺序整数;

  • 数据7:105个逆序整数;

  • 数据8:105个基本有序的整数;

  • 数据9:105个随机正整数,每个数字不超过1000。
    输入格式:
    输入第一行给出正整数N(≤105),随后一行给出N个(长整型范围内的)整数,其间以空格分隔。
    输出格式:
    在一行中输出从小到大排序后的结果,数字间以1个空格分隔,行末不得有多余空格。
    输入样例:

    11
    4 981 10 -17 0 -20 29 50 8 43 -5

    输出样例:

    -20 -17 -5 0 4 8 10 29 43 50 981

代码长度限制:16 KB

时间限制:10000 ms

内存限制:64 MB

答案:

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int i,n;
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
cout<<a[0];
for(i=1;i<n;i++)
cout<<" "<<a[i];
return 0;
}

十、2024.5.19——数据结构图作业

数据结构-10

(1)编程题

数据结构-10.1

7-1 哥尼斯堡的“七桥问题”

数据结构-7-1

作者 DS课程组

单位 浙江大学

哥尼斯堡是位于普累格河上的一座城市,它包含两个岛屿及连接它们的七座桥,如下图所示。

可否走过这样的七座桥,而且每桥只走过一次?瑞士数学家欧拉(Leonhard Euler,1707—1783)最终解决了这个问题,并由此创立了拓扑学。

这个问题如今可以描述为判断欧拉回路是否存在的问题。欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个无向图,问是否存在欧拉回路?

输入格式:

输入第一行给出两个正整数,分别是节点数N (1≤N≤1000)和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。

输出格式:

若欧拉回路存在则输出1,否则输出0。

输入样例1:

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

输出样例1:

1

输入样例2:

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

输出样例2:

0

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自哥尼斯堡的“七桥问题”(29行简单易懂) - 编程好6博客 (bianchenghao6.com))

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int MAP[maxn][maxn];
int du[maxn], vis[maxn];
int N, M, K, A, B;
void DFS(int x)
{
vis[x] = 1;
for (int i = 1; i <= N; i++)
if (MAP[x][i] && !vis[i])
DFS(i);
}
int main()
{
cin >> N >> M;
while (M--)
{
cin >> A >> B;
MAP[A][B] = MAP[B][A] = 1;
du[A]++, du[B]++;
}
for (int i = 1; i <= N; i++)
if (du[i] & 1)return cout << 0 << endl, 0;
DFS(1);
for (int i = 1; i <= N; i++)
if (!vis[i])return cout << 0 << endl, 0;
return cout << 1 << endl, 0;
}

7-2 分而治之

数据结构-7-2

作者 陈越

单位 浙江大学

分而治之,各个击破是兵家常用的策略之一。在战争中,我们希望首先攻下敌方的部分城市,使其剩余的城市变成孤立无援,然后再分头各个击破。为此参谋部提供了若干打击方案。本题就请你编写程序,判断每个方案的可行性。

输入格式:

输入在第一行给出两个正整数 N 和 M(均不超过10 000),分别为敌方城市个数(于是默认城市从 1 到 N 编号)和连接两城市的通路条数。随后 M 行,每行给出一条通路所连接的两个城市的编号,其间以一个空格分隔。在城市信息之后给出参谋部的系列方案,即一个正整数 K (≤ 100)和随后的 K 行方案,每行按以下格式给出:

Np v[1] v[2] ... v[Np]

其中 Np 是该方案中计划攻下的城市数量,后面的系列 v[i] 是计划攻下的城市编号。

输出格式:

对每一套方案,如果可行就输出YES,否则输出NO。

输入样例:

10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 10
2 4
5
4 10 3 8 4
6 6 1 7 5 4 9
3 1 8 4
2 2 8
7 9 8 7 6 5 4 2

输出样例:

NO
YES
YES
NO
NO

代码长度限制:16 KB

时间限制:600 ms

内存限制:64 MB

答案:(引用自7-12 分而治之 (25 分)(有图详解,巧用技巧,简单易懂)_pta分而治之-CSDN博客)

#include "bits/stdc++.h"
using namespace std;
int t[10001];//用来标记城市是否被攻陷
pair<int ,int> a[10001];//用来记录边,从起点到终点
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++)
{
int x,y;
cin>>x>>y;
a[i]={x,y};//记录边
}
int k;
cin>>k;
while(k--)//对于指挥部的k种方案
{
memset(t,1,sizeof(t));//置1表示所以的城市都还完好
int k1,t1=0;//记录方案是否可行
cin>>k1;
while(k1--)
{
int k2;
cin>>k2;
t[k2]=0;//该城市被攻陷了
}
for(int i=0;i<m;i++)
{
if(t[a[i].first]&&t[a[i].second]) t1=1;//注意是&&,即当这两个城市有边且都没有被攻陷的时候,t1成立
}
if(t1) cout<<"NO"<<endl;//那么就是没有全部分开,方案不可行
else cout<<"YES"<<endl;//反之则可行
}
}

7-3 判断两点之间是否存在路径

数据结构-7-3

作者 张瑞霞

单位 桂林电子科技大学

本题要求输出两个顶点之间是否存在路径

输入格式:

输入包括两部分,第一部分是邻接矩阵表示方法中对应1的两个顶点,用0 0 表示结束
第二部分是两个顶点,例如 Vi和Vj

输出格式:

如果Vi和Vj存在路径,输出1;否则输出0

输入样例:

0 1
1 0
0 4
4 0
1 4
4 1
1 2
2 1
1 3
3 1
2 3
3 2
4 5
5 4
4 6
6 4
0 0
0 5

输出样例:

1

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自7-3 电话聊天狂人 (25 分)-CSDN博客)

#include <stdio.h>
#include <stdbool.h>
#define max 100
int main() {
int adj_mat[max][max];
for (int i = 0; i < max; i++)
{
for (int j = 0; j < max; j++)
{
adj_mat[i][j] = 0;
}
}
int data, start, end;
while (scanf("%d %d", &start, &end) == 2)
{
if (start == 0 && end == 0)
break;
for (int i = 0; i < max; i++)
{
scanf("%d", &data);
while (data-- > 0)
{
int neighbor;
scanf("%d", &neighbor);
adj_mat[start][neighbor] = 1;
adj_mat[neighbor][start] = 1;
}
}
bool visited[max];
for (int i = 0; i < max; i++)
visited[i] = false;
int queue[max], front = 0, rear = 0;
queue[rear++] = start;
visited[start] = true;
while (front < rear)
{
int curr = queue[front++];
if (curr == end)
{
printf("1\n");
break;
}
for (int i = 0; i < max; i++)
{
if (adj_mat[curr][i] == 1 && !visited[i])
{
queue[rear++] = i;
visited[i] = true;
}
}
}
if (front == rear)
printf("0\n");
}
return 0;
}

7-4 顶点的度

数据结构-7-4

作者 黄龙军

单位 绍兴文理学院

求无向图G中各顶点的度。建议分别采用邻接矩阵和邻接表这两种不同的存储结构完成。

输入格式:

首先输入一个正整数T,表示测试数据的组数,然后是T组测试数据。每组测试第一行输入2个整数n、m(2≤n≤26,1≤m≤n(n-1)/2),分别表示顶点数、边数;然后输入m行,每行包含两个顶点Ai、Bi(大写字母表示),表示Ai和Bi之间有一条边。

输出格式:

对于每组测试,在一行上依顶点的字典序输出各顶点的度,每两个数据之间留一个空格。

输入样例:

1
5 4
A C
A B
B D
E C

输出样例:

2 2 2 1 1

来源:

[1] 黄龙军, 等. 数据结构与算法, 上海:上海交通大学出版社, 2022.7. ISBN: 9787313269881
[2] 黄龙军, 等. 数据结构与算法(Python版),上海: 上海交通大学出版社, 2023. ISBN: 9787313280732

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
#include <stdlib.h>

int main() {
int t,m,n;
scanf("%d",&t);
for(int h=0;h<t;h++)
{
scanf("%d %d",&n,&m);
int a[10000],d[10000]={0};
char cd,rd,c1,r1;
getchar();
for(int i=0;i<m;i++)
{
scanf("%c %c",&cd,&rd);
c1=cd-'A';
r1=rd-'A';
d[c1]++;
d[r1]++;
getchar();
}
printf("%d",d[0]);
for(int j=1;j<n;j++)
printf(" %d",d[j]);
printf("\n");
}
return 0;
}

7-5 入度与出度

数据结构-7-5

作者 黄龙军

单位 绍兴文理学院

求有向图G中各顶点的入度与出度。建议分别采用邻接矩阵和邻接表这两种不同的存储结构完成。

输入格式:

首先输入一个正整数T,表示测试数据的组数,然后是T组测试数据。每组测试第一行输入2个整数n、m(2≤n≤26,1≤m≤n(n-1)/2),分别表示顶点数、边数;然后输入m行,每行包含两个顶点Ai、Bi(大写字母表示),表示Ai到Bi有一条有向边。

输出格式:

对于每组测试,输出n行,依顶点的字典序在每行上输出各顶点的入度和出度(数据之间留一个空格)。

输入样例:

1
5 4
A C
A B
B D
E C

输出样例:

0 2
1 1
2 0
1 0
0 1

来源:

[1] 黄龙军, 等. 数据结构与算法, 上海:上海交通大学出版社, 2022.7. ISBN: 9787313269881
[2] 黄龙军, 等. 数据结构与算法(Python版),上海: 上海交通大学出版社, 2023. ISBN: 9787313280732**

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
#include <stdlib.h>

int main() {
int t,m,n;
scanf("%d",&t);
for(int h=0;h<t;h++)
{
scanf("%d %d",&n,&m);
int a[10000],r[10000]={0},c[10000]={0};
char cd,rd,c1,r1;
getchar();
for(int i=0;i<m;i++)
{
scanf("%c %c",&cd,&rd);
c1=cd-'A';
r1=rd-'A';
c[c1]++;
r[r1]++;
getchar();
}
for(int j=0;j<n;j++)
printf("%d %d\n",r[j],c[j]);
}
return 0;
}

九、2024.5.12——二分查找哈希作业

数据结构-9

(1)编程题

数据结构-9.1

7-1 悄悄关注

数据结构-7-1

作者 陈越

单位 浙江大学

新浪微博上有个“悄悄关注”,一个用户悄悄关注的人,不出现在这个用户的关注列表上,但系统会推送其悄悄关注的人发表的微博给该用户。现在我们来做一回网络侦探,根据某人的关注列表和其对其他用户的点赞情况,扒出有可能被其悄悄关注的人。

输入格式:

输入首先在第一行给出某用户的关注列表,格式如下:
人数N 用户1 用户2 …… 用户N

其中N是不超过5000的正整数,每个用户i(i=1, …, N)是被其关注的用户的ID,是长度为4位的由数字和英文字母组成的字符串,各项间以空格分隔。

之后给出该用户点赞的信息:首先给出一个不超过10000的正整数M,随后M行,每行给出一个被其点赞的用户ID和对该用户的点赞次数(不超过1000),以空格分隔。注意:用户ID是一个用户的唯一身份标识。题目保证在关注列表中没有重复用户,在点赞信息中也没有重复用户。

输出格式:

我们认为被该用户点赞次数大于其点赞平均数、且不在其关注列表上的人,很可能是其悄悄关注的人。根据这个假设,请你按用户ID字母序的升序输出可能是其悄悄关注的人,每行1个ID。如果其实并没有这样的人,则输出“Bing Mei You”。

输入样例1:

10 GAO3 Magi Zha1 Sen1 Quan FaMK LSum Eins FatM LLao
8
Magi 50
Pota 30
LLao 3
Ammy 48
Dave 15
GAO3 31
Zoro 1
Cath 60

输出样例1:

Ammy
Cath
Pota

输入样例2:

11 GAO3 Magi Zha1 Sen1 Quan FaMK LSum Eins FatM LLao Pota
7
Magi 50
Pota 30
LLao 48
Ammy 3
Dave 15
GAO3 31
Zoro 29

输出样例2:

Bing Mei You

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-1 悄悄关注 (20分)-CSDN博客)

#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<cstdio>
using namespace std;
struct weibo
{
string name;//用户名
int num;//点赞次数
}wb[10005];

int main()
{
int n,m;
map<string,int> mp;//存关注的ID,
cin>>n;
set<string> st;//存可能悄悄关注的用户ID
for(int i=0;i<n;i++)
{
string a;
cin>>a;
mp[a]=1;//对存入哪一个ID可以随意赋值
}
cin>>m;
getchar();
double s=0;
for(int i=0;i<m;i++)
{
cin>>wb[i].name >>wb[i].num ;
s+=wb[i].num ;//统计点赞总数,之后算平均值
}
s/=m;
int flag=0;
for(int i=0;i<m;i++)
{
if(wb[i].num >s&&mp.count(wb[i].name )==false )//如果点赞数超过平均数并且不再关注的人里面
{
flag=1;
st.insert(wb[i].name );//将该用户ID插入set容器中
}
}
if(flag==0)
cout<<"Bing Mei You";
else
{
for(set<string>::iterator it=st.begin();it!=st.end();it++)
{
cout<<*it<<endl;
}
}
}

7-2 单身狗

数据结构-7-2

作者 陈越

单位 浙江大学

“单身狗”是中文对于单身人士的一种爱称。本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱。

输入格式:

输入第一行给出一个正整数 N(≤50000),是已知夫妻/伴侣的对数;随后 N 行,每行给出一对夫妻/伴侣——为方便起见,每人对应一个 ID 号,为 5 位数字(从 00000 到 99999),ID 间以空格分隔;之后给出一个正整数 M(≤10000),为参加派对的总人数;随后一行给出这 M 位客人的 ID,以空格分隔。题目保证无人重婚或脚踩两条船。

输出格式:

首先第一行输出落单客人的总人数;随后第二行按 ID 递增顺序列出落单的客人。ID 间用 1 个空格分隔,行的首尾不得有多余空格。

输入样例:

3
11111 22222
33333 44444
55555 66666
7
55555 44444 10000 88888 22222 11111 23333

输出样例:

5
10000 23333 44444 55555 88888

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

答案:(引用自PTA 1065 单身狗 (25 分) C++实现_找出单身狗c++-CSDN博客)

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <numeric>
#include <map>

using namespace std;

int main()
{
int n;
cin >> n; //情侣总数

vector<int> lovers(100005, -1); //建立情侣数对应关系
for (int i = 0; i < n; i++)
{
int mate1, mate2;
cin >> mate1 >> mate2;

lovers[mate1] = mate2;
lovers[mate2] = mate1;
}

int total;
cin >> total; //参加派对的总人数

vector<int> res;
for (int i = 0; i < total; i++)
{
int temp;
cin >> temp;
res.push_back(temp);
}

//将参加派对的数字按升序排序,便于后续处理
sort(res.begin(), res.end());

vector<int> ans; //存单身数字
for (int i = 0; i < res.size(); i++)
{
int key = 0;
for (int j = 0; j < res.size(); j++)
{
if (lovers[res[i]] == res[j])
{
key = 1;
break;
}
}

if (key == 0)
{
ans.push_back(res[i]);
}
}

cout << ans.size() << endl; //输出单身总数
int flag = 1; //输出控制
for (int i = 0; i < ans.size(); i++)
{
if (flag > 1)
{
cout << " ";
}
printf("%05d",ans[i]);
flag++;
}
}

7-3 电话聊天狂人

数据结构-7-3

作者 DS课程组

单位 浙江大学

给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。

输入格式:

输入首先给出正整数N(≤105),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。

输出格式:

在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。

输入样例:

4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832

输出样例:

13588625832 3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-3 电话聊天狂人 (25 分)-CSDN博客)

#include<iostream>
#include<map>
using namespace std;
map<string ,int >mp;
map<string ,int >::iterator it;
int main(){
int n;
cin>>n;
int max=0;
string maxid;
for(int i=0;i<n;i++){
string s1,s2;
cin>>s1>>s2;
mp[s1]++;
mp[s2]++;
if(mp[s1]>max){
max=mp[s1];
maxid=s1;
}
if(mp[s2]>max){
max=mp[s2];
maxid=s2;
}
}
int t=0;
string a;
for(it=mp.begin();it!=mp.end();++it){
if(it->second==max){
if(t==0) a=it->first;
t++;
}
}
if(t>1)
cout<<a<<" "<<max<<" "<<t<<endl;
else
cout<<a<<" "<<max<<endl;
return 0;
}

7-4 航空公司VIP客户查询

数据结构-7-4

作者 DS课程组

单位 浙江大学

不少航空公司都会提供优惠的会员服务,当某顾客飞行里程累积达到一定数量后,可以使用里程积分直接兑换奖励机票或奖励升舱等服务。现给定某航空公司全体会员的飞行记录,要求实现根据身份证号码快速查询会员里程积分的功能。

输入格式:

输入首先给出两个正整数N(≤105)和K(≤500)。其中K是最低里程,即为照顾乘坐短程航班的会员,航空公司还会将航程低于K公里的航班也按K公里累积。随后N行,每行给出一条飞行记录。飞行记录的输入格式为:18位身份证号码(空格)飞行里程。其中身份证号码由17位数字加最后一位校验码组成,校验码的取值范围为0~9和x共11个符号;飞行里程单位为公里,是(0, 15 000]区间内的整数。然后给出一个正整数M(≤105),随后给出M行查询人的身份证号码。

输出格式:

对每个查询人,给出其当前的里程累积值。如果该人不是会员,则输出No Info。每个查询结果占一行。

输入样例:

4 500
330106199010080419 499
110108198403100012 15000
120104195510156021 800
330106199010080419 1
4
120104195510156021
110108198403100012
330106199010080419
33010619901008041x

输出样例:

800
15000
1000
No Info

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-45 航空公司VIP客户查询 (25分)_航空公司vip客户查询分析-CSDN博客)

#include <stdio.h>
#include <string.h>

#define MAXLENGTH 100007

typedef struct Record
{
char number[19]; // 身份证号
int distance; // 飞行距离
int next; // 同一个哈希值的链表里的指针
}Record;

Record records[MAXLENGTH]; // 当作链表用
int head[MAXLENGTH]; // 哈希表,存放链表头结点在records表中的下标
int count; // records表中已经插入的结点数目

void solution();
int hash(char *number); // 哈希函数,对身份证号进行散列
void insert(char *number, int distance); // 将飞行记录信息插入到表中
int find(char *number); // 根据身份证号查找飞行记录

int main()
{
solution();
}

void solution()
{
memset(head, -1, sizeof head);
int n, k;
scanf("%d %d", &n, &k);
char number[19];
int distance;
for (int i = 0; i < n; i++)
{
scanf("%s %d", number, &distance);
if (distance < k) distance = k;
insert(number, distance);
}
int m;
scanf("%d", &m);
int pos = -1;
for (int i = 0; i < m; i++)
{
scanf("%s", number);
pos = find(number);
if (pos == -1) printf("No Info\n");
else printf("%d\n", records[pos].distance);
}

}

/**
* @brief 哈希函数
* @param number 身份证号
* @return 哈希值
*/
int hash(char *number)
{
long long res = 0;
for (int i = 0; i < 17; i++) // 最后一位是前17位的校验值,可以不考虑,并不影响唯一性
res = 10 * res + (number[i] - '0');
return res % MAXLENGTH;
}

/**
* @brief 将飞行记录信息插入到哈希表中
* @param number 身份证号
* @param distance 飞行距离
*/
void insert(char *number, int distance)
{
int h = hash(number);
for (int i = head[h]; i != -1; i = records[i].next)
{
if (!strcmp(records[i].number, number))
{
records[i].distance += distance;
return;
}
}
records[count].distance += distance;
strncpy(records[count].number, number, 18);
records[count].next = head[h];
head[h] = count++;
}

int find(char *number)
{
int h = hash(number);
for (int i = head[h]; i != -1; i = records[i].next)
if (!strcmp(records[i].number, number)) return i;
return -1;
}

7-5 词频统计

数据结构-7-5

作者 DS课程组

单位 浙江大学

请编写程序,对一段英文文本,统计其中所有不同单词的个数,以及词频最大的前10%的单词。

所谓“单词”,是指由不超过80个单词字符组成的连续字符串,但长度超过15的单词将只截取保留前15个单词字符。而合法的“单词字符”为大小写字母、数字和下划线,其它字符均认为是单词分隔符。

输入格式:

输入给出一段非空文本,最后以符号#结尾。输入保证存在至少10个不同的单词。

输出格式:

在第一行中输出文本中所有不同单词的个数。注意“单词”不区分英文大小写,例如“PAT”和“pat”被认为是同一个单词。

随后按照词频递减的顺序,按照词频:单词的格式输出词频最大的前10%的单词。若有并列,则按递增字典序输出。

输入样例:

This is a test.

The word "this" is the word with the highest frequency.

Longlonglonglongword should be cut off, so is considered as the same as longlonglonglonee. But this_8 is different than this, and this, and this...#
this line should be ignored.

输出样例:(注意:虽然单词the也出现了4次,但因为我们只要输出前10%(即23个单词中的前2个)单词,而按照字母序,the排第3位,所以不输出。)

23
5:this
4:is

感谢武汉理工大学的郭小兵老师修正测试数据!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自PTA 词频统计 - 知乎 (zhihu.com))

#include <iostream>
#include <string>
#include <map>

std::map<std::string, int> counter;

bool solve(std::string &str){
counter[str]++;
str.erase();
return true;
}
bool printmax(){
std::map<std::string, int>::iterator maximum = counter.begin();
for(std::map<std::string, int>::iterator it = maximum; it != counter.end(); it++)
if(it->second > maximum->second)
maximum = it;
std::cout << maximum->second << ":" << maximum->first << std::endl;
counter.erase(maximum);
return true;
}
int main(){
std::string buffer, word;
bool flag = false;
while(std::cin>>buffer){
for(int i=0; i<buffer.length(); i++){
if(buffer[i] == '#' && (flag = true)) break;
if(word.length() >= 15){
solve(word);
break;
}
if(buffer[i] >= 'A' && buffer[i] <= 'Z'){
word += buffer[i] + 32;
}else if(buffer[i] >= 'a' && buffer[i] <= 'z' || buffer[i]>='0' && buffer[i]<='9' || buffer[i] == '_'){
word += buffer[i];
}else if(word.length() > 0){
solve(word);
continue;
}
}
if(word.length() > 0)
solve(word);
if(flag) break;
}
std::cout << counter.size() << std::endl;
for(int i=0, ecx=counter.size()/10; i<ecx; i++)
printmax();
return 0;
}

7-6 整型关键字的平方探测法散列

数据结构-7-6

作者 陈越

单位 浙江大学

本题的任务很简单:将给定的无重复正整数序列插入一个散列表,输出每个输入的数字在表中的位置。所用的散列函数是 H(key)=key%TSize,其中 TSize 是散列表的表长。要求用平方探测法(只增不减,即H(Key)+i2)解决冲突。

注意散列表的表长最好是个素数。如果输入给定的表长不是素数,你必须将表长重新定义为大于给定表长的最小素数。

输入格式:

首先第一行给出两个正整数 MSize(≤104)和 N(≤MSize),分别对应输入的表长和输入数字的个数。随后第二行给出 N 个不重复的正整数,数字间以空格分隔。

输出格式:

在一行中按照输入的顺序给出每个数字在散列表中的位置(下标从 0 开始)。如果某个数字无法插入,就在其位置上输出 -。输出间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

4 4
10 6 4 15

输出样例:

0 1 4 -

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自整型关键字的平方探测法散列 (25 分)【详细解析】_7-2 整型关键字的平方探测法散列-CSDN博客)

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
int is(int n) {
if(n == 1)return 0;
if(n == 2 || n == 3)return 1;
if(n % 6 != 1 && n % 6 != 5)return 0;
for(int i = 5;i * i <= n;i += 6)
if(n % i == 0 || n % (i + 2) == 0)return 0;
return 1;
}
int main() {
int m,n;
int s,p,v[10007] = {0};
scanf("%d %d",&m,&n);
while(!is(m))m ++;
for(int i = 0;i < n;i ++) {
p = -1;
scanf("%d",&s);
for(int j = 0;j < m;j ++) {
if(!v[(s + j * j) % m]) {
v[(s + j * j) % m] = 1;
p = (s + j * j) % m;
break;
}
}
if(i)putchar(' ');
if(p == -1)printf("-");
else printf("%d",p);
}
}

八、2024.5.12——数据结构堆作业

数据结构-8

(1)编程题

数据结构-8.1

7-1 堆中的路径

数据结构-7-1

作者 陈越

单位 浙江大学

将一系列给定数字插入一个初始为空的最小堆 h。随后对任意给定的下标 i,打印从第 i 个结点到根结点的路径。

输入格式:

每组测试第 1 行包含 2 个正整数 n 和 m (≤103),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间 [−104,104] 内的 n 个要被插入一个初始为空的小顶堆的整数。最后一行给出 m 个下标。

输出格式:

对输入中给出的每个下标 i,在一行中输出从第 i 个结点到根结点的路径上的数据。数字间以 1 个空格分隔,行末不得有多余空格。

输入样例:

5 3
46 23 26 24 10
5 4 3

输出样例:

24 23 10
46 23 10
26 10

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include<iostream>
#include<algorithm>
using namespace std;
void heapjian(int a[],int n,int m)
{
for(int j=n*2;j<=m;j=j*2)
{
if(j<m&&a[j]>a[j+1])
j++;
if(a[n]<a[j])
break;
else
{
int t=a[j];
a[j]=a[n];
a[n]=t;
}
n=j;
}
}
int main()
{
int n,m,k;
cin>>n>>m;
int a[10003];
for(int i=1;i<=n;i++)
{
cin>>a[i];
if(i!=1)
{
for(int j=i/2;j>=1;j--)
{
heapjian(a,j,i);
}
}
}
int j;
for(int i=0;i<m;i++)
{
cin>>k;
cout<<a[k];
for(j=k/2;j>=1;j=j/2)
cout<<" "<<a[j];

cout<<"\n";
}
return 0;
}

7-2 关于堆的判断

数据结构-7-2

作者 陈越

单位 浙江大学

将一系列给定数字顺序插入一个初始为空的最小堆。随后判断一系列相关命题是否为真。命题分下列几种:

  • x is the root:x是根结点;
  • x and y are siblings:x和y是兄弟结点;
  • x is the parent of y:x是y的父结点;
  • x is a child of y:x是y的一个子结点。

输入格式:

每组测试第 1 行包含 2 个正整数 n(≤ 1000)和 m(≤ 20),分别是插入元素的个数、以及需要判断的命题数。下一行给出区间 [−10000,10000] 内的 n 个要被插入一个初始为空的最小堆的整数。之后 m 行,每行给出一个命题。题目保证命题中的结点键值都是存在的。

输出格式:

对输入的每个命题,如果其为真,则在一行中输出 T,否则输出 F。

输入样例:

5 4
46 23 26 24 10
24 is the root
26 and 23 are siblings
46 is the parent of 23
23 is a child of 10

输出样例:

F
T
F
T

题目引用自团体程序设计天梯赛真题(2016年)。

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

答案:(引用自7-12 关于堆的判断_7-1 关于堆的判断-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
int H[10010]={10005};
int n;
int find(int x)
{
for(int i=1;i<=n;i++)
{
if(H[i]==x)
return i;
}
return -1;
}
int main()
{
int m,t;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>H[i];
t=i;
while(t>1&&H[t]<H[t/2])
{
swap(H[t],H[t/2]);
t/=2;
}
}
while(m--)
{
string s;
int x;
cin>>x;
cin>>s;
if(s=="and")
{
int y;
cin>>y;
cin>>s;
cin>>s;
if(H[find(x)/2]==H[find(y)/2])
cout<<"T"<<endl;
else
cout<<"F"<<endl;
}
else
{
cin>>s;
if(s=="a")
{
int y;
cin>>s;
cin>>s;
cin>>y;
if(H[find(x)/2]==y)
cout<<"T"<<endl;
else
cout<<"F"<<endl;
}
else
{
cin>>s;
if(s=="root")
{
if(H[1]==x)
cout<<"T"<<endl;
else
cout<<"F"<<endl;
}
else
{
int y;
cin>>s;
cin>>y;
if(H[find(y)/2]==x)
cout<<"T"<<endl;
else
cout<<"F"<<endl;
}
}
}
}
return 0;
}

7-3 堆的操作

数据结构-7-3

作者 周强

单位 青岛大学

编写代码,实现最小堆(Min-Heap)的操作。

输入格式:

第一行是两个不大于1000的正整数N和K,用空格间隔。其中N是堆的容量,需创建一个容量为N的堆。

接下来K行,是对这个堆的依次的K项插入或删除操作:用 1 x 表示插入元素x;用 -1 表示删除堆顶。

接下来一行是一个不大于1000的正整数M,

接下来一行是M个整数(在整型范围内),用空格间隔,

要求将这M个整数组成的列表调整为一个最小堆。

输出格式:

对于第一个堆的K项操作,每次操作后,在一行中依次序打印堆元素,元素间使用1个空格分隔;

对于第二个堆,在调整完成后,在一行中依次序打印堆元素,元素间使用1个空格分隔。

输入样例:

10 8
1 1
1 2
1 3
1 4
1 5
-1
1 6
-1
8
1 2 3 4 5 6 7 8

输出样例:

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

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自堆的操作_编写代码,实现最小堆(min-heap)的操作。 输入格式: 第一行是两个不大于1000的正整-CSDN博客)

#include<iostream>

using namespace std;

struct heap{
int data[1001];
int size;
int capacity;
heap(int cap){
size = 0;
capacity = cap;
}
};

typedef struct heap* Heap;

void percolateUp(Heap h, int index){
int i, tmp = h->data[index];
for(i = index; i / 2 > 0 && tmp < h->data[i / 2]; i /= 2)
h->data[i] = h->data[i / 2];
h->data[i] = tmp;
}

void percolateDown(Heap h, int index){
int i, tmp = h->data[index], child;
for(i = index; i * 2 <= h->size; i = child){
child = i * 2;
if(child < h->size && h->data[child + 1] < h->data[child]) child++;
if(tmp > h->data[child]) h->data[i] = h->data[child];
else break;
}
h->data[i] = tmp;
}

void insert(Heap h, int key){
if(h->size == h->capacity) return ;
h->data[++h->size] = key;
percolateUp(h, h->size);
}

void remove(Heap h){
if(h->size == 0) return ;
h->data[1] = h->data[h->size];
h->size--;
percolateDown(h, 1);
}

void print(Heap h){
for(int i = 1; i < h->size; i++)
cout << h->data[i] << ' ';
cout << h->data[h->size] << endl;
}

int main(){
int N, K, M;
int tmp;
cin >> N >> K;
Heap h = new heap(N);
for(int i = 0; i < K; i++){
cin >> tmp;
if(tmp == 1){
cin >> tmp;
insert(h, tmp);
}else{
remove(h);
}
print(h);
}
cin >> M;
Heap h2 = new heap(1001);
for(int i = 0; i < M; i++){
cin >> tmp;
h2->data[++h2->size] = tmp;
}
for(int i = h2->size / 2; i > 0; i--){
percolateDown(h2, i);
}
print(h2);
return 0;
}

7-4 修理牧场

数据结构-7-4

作者 DS课程组

单位 浙江大学

农夫要修理牧场的一段栅栏,他测量了栅栏,发现需要 n 块木头,每块木头长度为整数 li​ 个长度单位,于是他购买了一条很长的、能锯成 n 块的木头,即该木头的长度是 li​ 的总和。

但是农夫自己没有锯子,请人锯木的酬金跟这段木头的长度成正比。为简单起见,不妨就设酬金等于所锯木头的长度。例如,要将长度为 20 的木头锯成长度为 8、7 和 5 的三段,第一次锯木头花费 20,将木头锯成 12 和 8;第二次锯木头花费 12,将长度为 12 的木头锯成 7 和 5,总花费为 32。如果第一次将木头锯成 15 和 5,则第二次锯木头花费 15,总花费为 35(大于 32)。

请编写程序帮助农夫计算将木头锯成 n 块的最少花费。

输入格式:

输入首先给出正整数 n(≤104),表示要将木头锯成 n 块。第二行给出 n 个正整数(≤50),表示每段木块的长度。

输出格式:

输出一个整数,即将木头锯成 n 块的最少花费。

输入样例:

8
4 5 1 2 1 3 1 1

输出样例:

49

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-1 修理牧场 (25 分)(最详解)(最容易理解的解题过程)_哈夫曼树—-修理牧场-CSDN博客)

//哈夫曼树
#include<bits/stdc++.h>
using namespace std;
int main(){
priority_queue <int,vector<int>,greater<int> > q;//优先队列 中 升序队列
int N,i,j,k,a[10000],d[10000],sum=0;
scanf("%d",&N);
for(i=0;i<N;i++){
scanf("%d",&a[i]);
}
for(i=0;i<N;i++){
q.push(a[i]);
}
while(!q.empty()&&q.size()!=1){
int temp1= q.top();//先访问 再弹出
q.pop();
int temp2= q.top();
q.pop();
int temp=temp1+temp2;
sum+=temp;
q.push(temp);
}
printf("%d",sum);
}

7-5 哈夫曼编码

数据结构-7-5

作者 陈越

单位 浙江大学

给定一段文字,如果我们统计出字母出现的频率,是可以根据哈夫曼算法给出一套编码,使得用此编码压缩原文可以得到最短的编码总长。然而哈夫曼编码并不是唯一的。例如对字符串”aaaxuaxz”,容易得到字母 ‘a’、’x’、’u’、’z’ 的出现频率对应为 4、2、1、1。我们可以设计编码 {‘a’=0, ‘x’=10, ‘u’=110, ‘z’=111},也可以用另一套 {‘a’=1, ‘x’=01, ‘u’=001, ‘z’=000},还可以用 {‘a’=0, ‘x’=11, ‘u’=100, ‘z’=101},三套编码都可以把原文压缩到 14 个字节。但是 {‘a’=0, ‘x’=01, ‘u’=011, ‘z’=001} 就不是哈夫曼编码,因为用这套编码压缩得到 00001011001001 后,解码的结果不唯一,”aaaxuaxz” 和 “aazuaxax” 都可以对应解码的结果。本题就请你判断任一套编码是否哈夫曼编码。

输入格式:

首先第一行给出一个正整数 N(2≤N≤63),随后第二行给出 N 个不重复的字符及其出现频率,格式如下:
c[1] f[1] c[2] f[2] … c[N] f[N]

其中c[i]是集合{‘0’ - ‘9’, ‘a’ - ‘z’, ‘A’ - ‘Z’, ‘_’}中的字符;f[i]是c[i]的出现频率,为不超过 1000 的整数。再下一行给出一个正整数 M(≤1000),随后是 M 套待检的编码。每套编码占 N 行,格式为:
c[i] code[i]

其中c[i]是第i个字符;code[i]是不超过63个’0’和’1’的非空字符串。

输出格式:

对每套待检编码,如果是正确的哈夫曼编码,就在一行中输出”Yes”,否则输出”No”。

注意:最优编码并不一定通过哈夫曼算法得到。任何能压缩到最优长度的前缀编码都应被判为正确。

输入样例:

7
A 1 B 1 C 1 D 3 E 3 F 6 G 6
4
A 00000
B 00001
C 0001
D 001
E 01
F 10
G 11
A 01010
B 01011
C 0100
D 011
E 10
F 11
G 00
A 000
B 001
C 010
D 011
E 100
F 101
G 110
A 00000
B 00001
C 0001
D 001
E 00
F 10
G 11

输出样例:

Yes
Yes
No
No**

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-1 哈夫曼编码 (30分)-阿里云开发者社区 (aliyun.com))

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
char c[100];//字符
int f[1000];//频率
priority_queue<int, vector<int>, greater<int> > q; //代表小顶堆的优先对列

int main(void)
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
getchar();
cin >> c[i] >> f[i];
q.push(f[i]); // 压入堆
}
int ans = 0; //ans即为哈弗曼树带权路径长度和,也就是所对应的哈夫曼编码的长度
while (q.size() > 1)
{
int x = q.top();
q.pop();
int y = q.top();
q.pop();
q.push(x + y);
ans += x + y; //求哈夫曼编码的长度
}
int M;
cin >> M;

// 编码套数
while (M--)
{
char code[66][66];
int sum = 0;
for (int j = 0; j < N; j++)
{
getchar();
char C;
cin >> C >> code[j];
sum += strlen(code[j]) * f[j];//根据字符串长度以及出现的频率求出哈夫曼编码长度
}
if (sum != ans)
printf("No\n");
else // 相同判断前缀
{
int flag = 0;
for (int j = 0; j < N; j++)
{
for (int l = 0; l < N; l++)
{
if (j != l)
{
if (strstr(code[l], code[j]) == &code[l][0])//查找字符串,如果找到了是相同前缀,就标记为No了
{
flag = 1;
break;
}
}
}
if (flag == 1)break;
}
if (flag == 1)
printf("No\n");
else
printf("Yes\n");
}
}
return 0;
}

七、2024.5.05——数据结构二叉树作业

数据结构-7

(1)编程题

数据结构-7.1

7-1 树的同构

数据结构-7-1

作者 陈越

单位 浙江大学

给定两棵树 T1​ 和 T2​。如果 T1​ 可以通过若干次左右孩子互换就变成 T2​,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。

图1

图2

现给定两棵树,请你判断它们是否是同构的。

输入格式:

输入给出2棵二叉树的信息。对于每棵树,首先在一行中给出一个非负整数 n (≤10),即该树的结点数(此时假设结点从 0 到 n−1 编号);随后 n 行,第 i 行对应编号第 i 个结点,给出该结点中存储的 1 个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出 “-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。

输出格式:

如果两棵树是同构的,输出“Yes”,否则输出“No”。

输入样例1(对应图1):

8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -

输出样例1:

Yes

输入样例2(对应图2):

8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4

输出样例2:

No

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-1 树的同构 【已改正】-CSDN博客)

#include <stdio.h>
#include <stdlib.h>

#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode {
ElementType Element;
Tree Left;
Tree Right;
} T1[MaxTree], T2[MaxTree];

Tree BuildTree( struct TreeNode T[] ) {
int N,i;
Tree Root=Null;//防止空树时,返回随机值,一定要做合适的初始化啊
ElementType cl,cr;
int check[MaxTree];
scanf("%d\n", &N);
if (N) {
for (i=0; i<N; i++)
check[i] = 0;
for (i=0; i<N; i++) {
scanf("%c %c %c\n", &T[i].Element, &cl, &cr);
if (cl != '-') {
T[i].Left = cl-'0';
check[T[i].Left] = 1;
} else
T[i].Left = Null;
/*对cr的对应处理 */
if (cr != '-') {
T[i].Right = cr-'0';
check[T[i].Right] = 1;
} else
T[i].Right = Null;
}
for (i=0; i<N; i++)
if (!check[i])
break;
Root = i;
}
return Root;
}

int Isomorphic ( Tree R1, Tree R2 ) {
if ( (R1==Null )&& (R2==Null) ) /* both empty */
return 1;

if ( ((R1==Null)&&(R2!=Null)) || ((R1!=Null)&&(R2==Null)) )
return 0; /* one of them is empty */

if ( T1[R1].Element != T2[R2].Element )
return 0; /* roots are different */

if ( ( T1[R1].Left == Null )&&( T2[R2].Left == Null ) )
/* both have no left subtree */
return Isomorphic( T1[R1].Right, T2[R2].Right );

if ( ((T1[R1].Left!=Null)&&(T2[R2].Left!=Null))&&
((T1[T1[R1].Left].Element)==(T2[T2[R2].Left].Element)) )
/* no need to swap the left and the right */
return ( Isomorphic( T1[R1].Left, T2[R2].Left ) &&
Isomorphic( T1[R1].Right, T2[R2].Right ) );

else /* need to swap the left and the right */
return ( Isomorphic( T1[R1].Left, T2[R2].Right) &&
Isomorphic( T1[R1].Right, T2[R2].Left ) );
}

int main() {
Tree R1, R2;
R1 = BuildTree(T1);
R2 = BuildTree(T2);
if (Isomorphic(R1, R2))
printf("Yes\n");
else
printf("No\n");
return 0;
}

7-2 愿天下有情人都是失散多年的兄妹

数据结构-7-2

作者 陈越

单位 浙江大学

呵呵。大家都知道五服以内不得通婚,即两个人最近的共同祖先如果在五代以内(即本人、父母、祖父母、曾祖父母、高祖父母)则不可通婚。本题就请你帮助一对有情人判断一下,他们究竟是否可以成婚?

输入格式:

输入第一行给出一个正整数N(2 ≤ N ≤104),随后N行,每行按以下格式给出一个人的信息:
本人ID 性别 父亲ID 母亲ID

其中ID是5位数字,每人不同;性别M代表男性、F代表女性。如果某人的父亲或母亲已经不可考,则相应的ID位置上标记为-1。

接下来给出一个正整数K,随后K行,每行给出一对有情人的ID,其间以空格分隔。

注意:题目保证两个人是同辈,每人只有一个性别,并且血缘关系网中没有乱伦或隔辈成婚的情况。

输出格式:

对每一对有情人,判断他们的关系是否可以通婚:如果两人是同性,输出Never Mind;如果是异性并且关系出了五服,输出Yes;如果异性关系未出五服,输出No。

输入样例:

24
00001 M 01111 -1
00002 F 02222 03333
00003 M 02222 03333
00004 F 04444 03333
00005 M 04444 05555
00006 F 04444 05555
00007 F 06666 07777
00008 M 06666 07777
00009 M 00001 00002
00010 M 00003 00006
00011 F 00005 00007
00012 F 00008 08888
00013 F 00009 00011
00014 M 00010 09999
00015 M 00010 09999
00016 M 10000 00012
00017 F -1 00012
00018 F 11000 00013
00019 F 11100 00018
00020 F 00015 11110
00021 M 11100 00020
00022 M 00016 -1
00023 M 10012 00017
00024 M 00022 10013
9
00021 00024
00019 00024
00011 00012
00022 00018
00001 00004
00013 00016
00017 00015
00019 00021
00010 00011

输出样例:

Never Mind
Yes
Never Mind
No
Yes
No
Yes
No
No

鸣谢用户 徐校波 修正数据!

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

答案:(引用自7-2 愿天下有情人都是失散多年的兄妹 (25 分)-CSDN博客)

#include <stdio.h>
#include <string.h>
#define maxsize 100005
struct node
{
int sex; //关于性别,1表示M, 2表示F
int fa ; //初始值全为-1,设为父母不可考
int mo ;
}Node[maxsize];
int flag; //全局变量标注是否出五服
int cnt[maxsize]; //五服存储
void Find(int id, int num)
{
if(num == 4) return;
if(Node[id].fa != -1)
{
if(cnt[Node[id].fa] == 1)
{
flag = 1;
return;
}
cnt[Node[id].fa] = 1;
Find(Node[id].fa, num+1);
}
if(Node[id].mo != -1)
{
if(cnt[Node[id].mo] == 1)
{
flag = 1;
return;
}
cnt[Node[id].mo] = 1;
Find(Node[id].mo, num+1);
}
}
int main()
{
int n;
scanf("%d", &n);
for(int i=0; i<maxsize; i++)
Node[i].fa = Node[i].mo = -1;
for(int i=0; i<n; i++)
{
int id, father, mother;
char x;
scanf("%d %c %d %d", &id, &x, &father, &mother);

if(x == 'M') Node[id].sex = 1;
else if(x == 'F') Node[id].sex = 2;

Node[id].fa = father;
Node[id].mo = mother;

// 父母的相应编号,需要标性别
if(father != -1) Node[father].sex = 1;
if(mother != -1) Node[mother].sex = 2;
}
int k;
scanf("%d", &k);
while (k--)
{
int n1, n2;
scanf("%d %d", &n1, &n2);
if(Node[n1].sex == Node[n2].sex) printf("Never Mind\n");
else
{
//清零数组及标记
memset(cnt, 0 , sizeof(cnt));
flag = 0;
//分别对以n1, n2为根节点进行遍历搜索
Find(n1, 0);
Find(n2, 0);
if(flag) printf("No\n");
else printf("Yes\n");
}
}
return 0;
}

7-3 小字辈

数据结构-7-3

作者 陈越

单位 浙江大学

本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。

输入格式:

输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。

输出格式:

首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。

输入样例:

9
2 6 5 5 -1 5 6 4 7

输出样例:

4
1 9

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-3 小字辈 (25分)_7-63 小字辈csdn-CSDN博客)

#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
#define max(a,b) a>b?a:b
using namespace std;
int a[100005];
vector<int>s[100005];
int start,n,maxx,flag;
void dfs(int x,int y){
a[x]=y;
maxx=max(maxx,y);
for(int i=0;i<s[x].size();i++){
dfs(s[x][i],y+1);
}
}
int main()
{
memset(a,0,sizeof(a));
scanf("%d",&n);
for(int i=1;i<=n;i++){
int t;
scanf("%d",&t);
if(t!=-1)
s[t].push_back(i);
else
start=i;
}
dfs(start,1);
printf("%d\n",maxx);
for(int i=1;i<=n;i++){
if(a[i]==maxx){
if(!flag){
printf("%d",i);
flag=1;
}else
printf(" %d",i);
}

}

}

7-5 二叉树叶结点值和最大层

数据结构-7-5

作者 朱允刚

单位 吉林大学

已知一棵非空二叉树结点的数据域为不等于0的整数,请编写程序找出该二叉树中叶结点数据值之和最大的层。

输入格式:

输入为一组用空格间隔的整数,个数不超过100个,表示带空指针信息的二叉树先根序列。

输出格式:

输出为一个整数,表示叶结点数据值之和最大的层,如果存在多个满足条件的层,则输出最下面一层。

输入样例1:

1 2 0 0 3 0 0

输出样例1

1

输入样例2:

1 -2 0 0 3 -1 0 0 -1 0 0

输出样例2:

2

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自二叉树叶结点值和最大层 (C语言)_输入为一组用空格间隔的整数,个数不超过100个,表示带空指针信息的二叉树先根序列-CSDN博客)

#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode{ //定义树节点结构;
int data;
struct TreeNode *lchild,*rchild;
}*Tree;
int a[100]={0};
void createTree(Tree *T){ //创建一棵二叉树;
int data;
scanf("%d",&data);
if(0==data){
*T=NULL;
}else{
*T=(Tree)malloc(sizeof(struct TreeNode));
(*T)->data=data;
createTree(&(*T)->lchild);
createTree(&(*T)->rchild);
}
}
void preorder(Tree T,int cnt){ //前序遍历记录每层叶子节点的值,注意:层数是从0开始的;
if(T){
if(!T->lchild&&!T->rchild)
a[cnt]+=T->data;
preorder(T->lchild,cnt+1);
preorder(T->rchild,cnt+1);
}
}
int Max(int max,int i){
while(i++<100)
if((a[i]!=0&&a[i]>=a[max])||a[max]==0)
max=i;
return max;
}
int main(){
Tree T;
createTree(&T);
preorder(T,0);
printf("%d\n",Max(0,0));
return 0;
}

7-6 病毒溯源

数据结构-7-6

作者 陈越

单位 浙江大学

病毒容易发生变异。某种病毒可以通过突变产生若干变异的毒株,而这些变异的病毒又可能被诱发突变产生第二代变异,如此继续不断变化。

现给定一些病毒之间的变异关系,要求你找出其中最长的一条变异链。

在此假设给出的变异都是由突变引起的,不考虑复杂的基因重组变异问题 —— 即每一种病毒都是由唯一的一种病毒突变而来,并且不存在循环变异的情况。

输入格式:

输入在第一行中给出一个正整数 N(≤104),即病毒种类的总数。于是我们将所有病毒从 0 到 N−1 进行编号。

随后 N 行,每行按以下格式描述一种病毒的变异情况:
k 变异株1 …… 变异株k

其中 k 是该病毒产生的变异毒株的种类数,后面跟着每种变异株的编号。第 i 行对应编号为 i 的病毒(0≤i<N)。题目保证病毒源头有且仅有一个。

输出格式:

首先输出从源头开始最长变异链的长度。

在第二行中输出从源头开始最长的一条变异链,编号间以 1 个空格分隔,行首尾不得有多余空格。如果最长链不唯一,则输出最小序列。

注:我们称序列 { a1​,⋯,an​ } 比序列 { b1​,⋯,bn​ } “小”,如果存在 1≤k≤n 满足 ai​=bi​ 对所有 i<k 成立,且 ak​<bk​。

输入样例:

10
3 6 4 8
0
0
0
2 5 9
0
1 7
1 2
0
2 3 1

输出样例:

4
0 4 9 1

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自7-10 病毒溯源 (25 分)_真题ok撒-CSDN博客)

#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n ,v;
vector<int> g[N] ,ans;
int in[N] ,pre[N];
void dfs (int x ,int depth) {
if (g[x].size() == 0 && depth > ans.size()) { 
ans.clear(); 
int now = x;
while (now != -1) {
ans.push_back(now);
now = pre[now];
}
return ;
}
for (int i = 0; i < g[x].size(); i++) {
v = g[x][i];
pre[v] = x;
dfs (v, depth + 1);
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
int k; cin >> k;
for (int j = 1; j <= k; j++) {
cin >> v;
in[v]++;
g[i].push_back(v);
}
sort (g[i].begin() ,g[i].end());
}
int root;
for (int i = 0; i < n; i++) {
if (!in[i]) {
root = i;
break;
}
}
pre[root] = -1;
dfs(root ,1);
cout << ans.size() << endl;
reverse (ans.begin() ,ans.end());
for (int i = 0; i < ans.size(); i++) {
if (i ) cout << ' ';
cout << ans[i];
}
return 0;
}

7-7 浪漫侧影

数据结构-7-7

作者 软件学院

单位 江西财经大学

“侧影”就是从左侧或者右侧去观察物体所看到的内容。例如上图中男生的侧影是从他右侧看过去的样子,叫“右视图”;女生的侧影是从她左侧看过去的样子,叫“左视图”。
520 这个日子还在打比赛的你,也就抱着一棵二叉树左看看右看看了……
我们将二叉树的“侧影”定义为从一侧能看到的所有结点从上到下形成的序列。例如下图这棵二叉树,其右视图就是 { 1, 2, 3, 4, 5 },左视图就是 { 1, 6, 7, 8, 5 }。

于是让我们首先通过一棵二叉树的中序遍历序列和后序遍历序列构建出一棵树,然后你要输出这棵树的左视图和右视图。

输入格式:

输入第一行给出一个正整数 N (≤20),为树中的结点个数。随后在两行中先后给出树的中序遍历和后序遍历序列。树中所有键值都不相同,其数值大小无关紧要,都不超过 int 的范围。

输出格式:

第一行输出右视图,第二行输出左视图,格式如样例所示。

输入样例:

在这里给出一组输入。例如:

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

输出样例:

在这里给出相应的输出。例如:

R: 1 2 3 4 5
L: 1 6 7 8 5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自L2-3 浪漫侧影 (25 分)_“侧影”就是从左侧或者右侧去观察物体所看到的内容。例如上图中男生的侧影是从他右侧看过去的样子,叫“右-CSDN博客)

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int N = 30;
typedef struct Node{
int v;
Node *l,*r;
}*Tree;

int a[N],b[N];

Tree build(int l1,int l2,int sz){
if(sz == 0) return nullptr;
Tree tree = (Tree)malloc(sizeof(Node));
int k = 0;
while(a[l1+k] != b[l2+sz-1]) k++; 
tree->v = b[l2+sz+-1];
tree->l = build(l1,l2,k);
tree->r = build(l1+k+1,l2+k,sz-(k+1));
return tree;
}

int main(){
int n;
cin>>n;
for(int i = 1; i <= n; i++) cin>>a[i];
for(int i = 1; i <= n; i++) cin>>b[i];
Tree root = build(1,1,n);
queue<Tree> que;
que.push(root);
vector<int> left,right;
while(que.size()){
int sz = que.size();
int first = -1, second = -1;
for(int i = 0; i < sz; i++){
auto tmp = que.front();
que.pop();
if(i == 0) first = tmp->v;
if(i == sz-1) second = tmp->v;
if(tmp->l) que.push(tmp->l);
if(tmp->r) que.push(tmp->r);
}
left.push_back(first);
right.push_back(second);
}
cout<<"R:";
for(auto num:right) cout<<' '<<num;
cout<<"\nL:";
for(auto num:left) cout<<' '<<num;

return 0;
}

六、2024.5.05——23数据结构24天梯赛

数据结构-6

(1)编程题

数据结构-6.1

L1-1 编程解决一切

数据结构-L1-1

作者 陈越

单位 浙江大学

编程解决一切 —— 本题非常简单,就请你直接在屏幕上输出这句话:“Problem? The Solution: Programming.”。

输入格式:

本题没有输入。

输出格式:

在一行中输出 Problem? The Solution: Programming.。

输入样例:

无

输出样例:

Problem? The Solution: Programming.

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
printf("Problem? The Solution: Programming."); 
return 0;
}

L1-2 再进去几个人

数据结构-L1-2

作者 陈越

单位 浙江大学

数学家、生物学家和物理学家坐在街头咖啡屋里,看着人们从街对面的一间房子走进走出。他们先看到两个人进去。时光流逝。他们又看到三个人出来。
物理学家:“测量不够准确。”
生物学家:“他们进行了繁殖。”
数学家:“如果现在再进去一个人,那房子就空了。”
下面就请你写个程序,根据进去和出来的人数,帮数学家算出来,再进去几个人,那房子就空了。

输入格式:

输入在一行中给出 2 个不超过 100 的正整数 A 和 B,其中 A 是进去的人数,B 是出来的人数。题目保证 B 比 A 要大。

输出格式:

在一行中输出使得房子变空的、需要再进去的人数。

输入样例:

4 7

输出样例:

3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d",b-a);
return 0;
}

L1-3 帮助色盲

数据结构-L1-3

作者 陈越

单位 浙江大学

在古老的红绿灯面前,红绿色盲患者无法分辨当前亮起的灯是红色还是绿色,有些聪明人通过路口的策略是这样的:当红灯或绿灯亮起时,灯的颜色无法判断,但前方两米内有同向行走的人,就跟着前面那人行动,人家走就跟着走,人家停就跟着停;如果当前是黄灯,那么很快就要变成红灯了,于是应该停下来。麻烦的是,当灯的颜色无法判断时,前方两米内没有人……
本题就请你写一个程序,通过产生不同的提示音来帮助红绿色盲患者判断当前交通灯的颜色;但当患者可以自行判断的时候(例如黄灯或者前方两米内有人),就不做多余的打扰。具体要求的功能为:当前交通灯为红灯或绿灯时,检测其前方两米内是否有同向行走的人 —— 如果有,则患者自己可以判断,程序就不做提示;如果没有,则根据灯的颜色给出不同的提示音。黄灯也不需要给出提示。

输入格式:

输入在一行中给出两个数字 A 和 B,其间以空格分隔。其中 A 是当前交通灯的颜色,取值为 0 表示红灯、1 表示绿灯、2 表示黄灯;B 是前方行人的状态,取值为 0 表示前方两米内没有同向行走的人、1 表示有。

输出格式:

根据输入的状态在第一行中输出提示音:dudu 表示前方为绿灯,可以继续前进;biii 表示前方为红灯,应该止步;- 表示不做提示。在第二行输出患者应该执行的动作:move 表示继续前进、stop 表示止步。

输入样例 1:

0 0

输出样例 1:

biii
stop

输入样例 2:

1 1

输出样例 2:

-
move

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
if(b==1)
{
printf("-\n");
if(a==1)
printf("move");
else if(a==0||a==2)
printf("stop");
}
else if(b==0)
{
if(a==0)
printf("biii\nstop");
else if(a==2)
printf("-\nstop");
else if(a==1)
printf("dudu\nmove");
}

return 0;
}

L1-4 四项全能

数据结构-L1-4

作者 陈越

单位 浙江大学

给定一个初始为空的队(队存储空间长度为10)和一系列进队、出队操作,请编写程序输出经过这些操作后队中的元素。队中元素值均为整数。(采用循环队列完成,禁用一个空间方法)

输入格式:

输入第1行为1个正整数n,表示操作个数;

第2行为给出的n个整数,非0元素表示进队,且此非0值即为进队元素,0元素表示出队。

输出格式:

第一行按出队顺序输出所有出队元素,以一个空格隔开;如果队空时做出队操作会输出”EMPTY”,如果队满时做进队操作会输出”FULL”。

第二行中输出队中所有元素,以一个空格隔开。

末尾均有一个空格。

输入样例:

12
3 1 2 0 0 -1 0 0 0 4 5 0

输出样例:

3 1 2 -1 EMPTY 4 
5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
int a,b;
scanf("%d %d",&a,&b);
int c,s=0;
for(int i=0;i<b;i++)
{
scanf("%d",&c);
s=s+c;
}
s=s-a*(b-1);
if(s>0)
printf("%d",s);
else
printf("0");
return 0;
}

L1-5 别再来这么多猫娘了!

数据结构-L1-5

作者 DAI, Longao

单位 杭州百腾教育科技有限公司

以 GPT 技术为核心的人工智能系统出现后迅速引领了行业的变革,不仅用于大量的语言工作(如邮件编写或文章生成等工作),还被应用在一些较特殊的领域——例如去年就有同学尝试使用 ChatGPT 作弊并被当场逮捕(全校被取消成绩)。相信聪明的你一定不会犯一样的错误!

言归正传,对于 GPT 类的 AI,一个使用方式受到不少年轻用户的欢迎——将 AI 变成猫娘:

image.png
部分公司使用 AI 进行网络营销,网友同样乐于使用“变猫娘”的方式进行反击。注意:图中内容与题目无关,如无法看到图片不影响解题。

当然,由于训练数据里并不区分道德或伦理倾向,因此如果不加审查,AI 会生成大量的、不一定符合社会公序良俗的内容。尽管关于这个问题仍有争论,但至少在比赛中,我们还是期望 AI 能用于对人类更有帮助的方向上,少来一点猫娘。

因此你的工作是实现一个审查内容的代码,用于对 AI 生成的内容的初步审定。更具体地说,你会得到一段由大小写字母、数字、空格及 ASCII 码范围内的标点符号的文字,以及若干个违禁词以及警告阈值,你需要首先检查内容里有多少违禁词,如果少于阈值个,则简单地将违禁词替换为<censored>;如果大于等于阈值个,则直接输出一段警告并输出有几个违禁词。

输入格式:

输入第一行是一个正整数 N (1≤N≤100),表示违禁词的数量。接下来的 N 行,每行一个长度不超过 10 的、只包含大小写字母、数字及 ASCII 码范围内的标点符号的单词,表示应当屏蔽的违禁词。
然后的一行是一个非负整数 k (0≤k≤100),表示违禁词的阈值。
最后是一行不超过 5000 个字符的字符串,表示需要检查的文字。
从左到右处理文本,违禁词则按照输入顺序依次处理;对于有重叠的情况,无论计数还是替换,查找完成后从违禁词末尾继续处理。

输出格式:

如果违禁词数量小于阈值,则输出替换后的文本;否则先输出一行一个数字,表示违禁词的数量,然后输出He Xie Ni Quan Jia!。

输入样例1:

5
MaoNiang
SeQing
BaoLi
WeiGui
BuHeShi
4
BianCheng MaoNiang ba! WeiGui De Hua Ye Keyi Shuo! BuYao BaoLi NeiRong.

输出样例1:

BianCheng <censored> ba! <censored> De Hua Ye Keyi Shuo! BuYao <censored> NeiRong.

输入样例2:

5
MaoNiang
SeQing
BaoLi
WeiGui
BuHeShi
3
BianCheng MaoNiang ba! WeiGui De Hua Ye Keyi Shuo! BuYao BaoLi NeiRong.

输出样例2:

3
He Xie Ni Quan Jia!

输入样例3:

2
AA
BB
3
AAABBB

输出样例3:

<censored>A<censored>B

输入样例4:

2
AB
BB
3
AAABBB

输出样例4:

AA<censored><censored>

输入样例5:

2
BB
AB
3
AAABBB

输出样例5:

AAA<censored>B

代码长度限制:16 KB

Java (javac)

时间限制:500 ms

内存限制:256 MB

其他编译器

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自大学生团体天梯赛(第十三届, 除最后两道)_l1-103 整数的持续性 分数 20 作者 陈越 单位 浙江大学 从任一给定的正整数 n 出-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
int n, k, cnt;
string s;
int main() {
cin >> n;
vector<string> st(n);
for (int i = 0; i < n; ++i) {
cin >> st[i];
}
cin >> k, getchar();
getline(cin, s);
vector<int> check(s.length());
for (auto& x : st) {
int pos = s.find(x);
while (pos != s.npos) {
s.erase(pos, x.length());
s.insert(pos, "/");
pos = s.find(x, pos);
++cnt;
}
}
if (cnt < k) {
int pos = s.find("/");
while (pos != s.npos) {
s.erase(pos, 1);
s.insert(pos, "<censored>");
pos = s.find("/", pos);
}
cout << s;
} else cout << cnt << "\nHe Xie Ni Quan Jia!";
return 0;
}

L1-7 整数的持续性

数据结构-L1-7

作者 陈越

单位 浙江大学

从任一给定的正整数 n 出发,将其每一位数字相乘,记得到的乘积为 n1​。以此类推,令 ni+1​ 为 ni​ 的各位数字的乘积,直到最后得到一个个位数 nm​,则 m 就称为 n 的持续性。例如 679 的持续性就是 5,因为我们从 679 开始,得到 6×7×9=378,随后得到 3×7×8=168、1×6×8=48、4×8=32,最后得到 3×2=6,一共用了 5 步。
本题就请你编写程序,找出任一给定区间内持续性最长的整数。

输入格式:

输入在一行中给出两个正整数 a 和 b(1≤a≤b≤109 且 (b−a)<103),为给定区间的两个端点。

输出格式:

首先在第一行输出区间 [a,b] 内整数最长的持续性。随后在第二行中输出持续性最长的整数。如果这样的整数不唯一,则按照递增序输出,数字间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

500 700

输出样例:

5
679 688 697

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
int a,b,c[20000]={0};
int x=10,y,z,f=0,i,max=-1,k;
scanf("%d %d",&a,&b);
if(a>=1&&b<=9)
{
printf("0\n");
printf("%d",a);
for(i=a+1;i<=b;i++)
{
printf(" %d",i);
}
return 0;
}
else
{
if(a<=9&&b>=10)
a=10;
for(i=a;i<=b;i++)
{
int j=i,x=1,y=1,f=1,s=0;
k=0;
if(i>=10)
{
while(f)
{
while(j>0)
{
x=j%10;
j=j/10;
y=y*x;
}
s++;
if(y>=10)
{
j=y;
y=1;
}
else
{
f=0;
}
}
if(s>max)
{
max=s;
}
}
else
{
max=max>s?max:s;
}
}
}
k=0;
printf("%d\n",max);
for(i=a;i<=b;i++)
{
int j=i,x=1,y=1,f=1,s=0;
if(max>=1)
{
while(f)
{
while(j>0)
{
x=j%10;
j=j/10;
y=y*x;
}
s++;
if(y>=10)
{
j=y;
y=1;
}
else
{
f=0;
}
}
if(s==max)
{
c[k]=i;
k++;
}
}
else
{
c[k]=i;
k++;
}
}
printf("%d",c[0]);
for(i=1;i<k;i++)
printf(" %d",c[i]);
return 0;
}

L1-8 九宫格

数据结构-L1-8

作者 陈越

单位 浙江大学

九宫格是一款数字游戏,传说起源于河图洛书,现代数学中称之为三阶幻方。游戏规则是:将一个 9×9 的正方形区域划分为 9 个 3×3 的正方形宫位,要求 1 到 9 这九个数字中的每个数字在每一行、每一列、每个宫位中都只能出现一次。
本题并不要求你写程序解决这个问题,只是对每个填好数字的九宫格,判断其是否满足游戏规则的要求。

输入格式:

输入首先在第一行给出一个正整数 n(≤10),随后给出 n 个填好数字的九宫格。每个九宫格分 9 行给出,每行给出 9 个数字,其间以空格分隔。

输出格式:

对每个给定的九宫格,判断其中的数字是否满足游戏规则的要求。满足则在一行中输出 1,否则输出 0。

输入样例:

3
5 1 9 2 8 3 4 6 7
7 2 8 9 6 4 3 5 1
3 4 6 5 7 1 9 2 8
8 9 2 1 4 5 7 3 6
4 7 3 6 2 8 1 9 5
6 5 1 7 3 9 2 8 4
9 3 4 8 1 6 5 7 2
1 6 7 3 5 2 8 4 9
2 8 5 4 9 7 6 1 3
8 2 5 4 9 7 1 3 6
7 9 6 5 1 3 8 2 4
3 4 1 6 8 2 7 9 5
6 8 4 2 7 1 3 5 9
9 1 2 8 3 5 6 4 7
5 3 7 9 6 4 2 1 8
2 7 9 1 5 8 4 6 3
4 5 8 3 2 6 9 7 1
1 6 3 7 4 9 5 8 3
81 2 5 4 9 7 1 3 6
7 9 6 5 1 3 8 2 4
3 4 1 6 8 2 7 9 5
6 8 4 2 7 1 3 5 9
9 1 2 8 3 5 6 4 7
5 3 7 9 6 4 2 1 8
2 7 9 1 5 8 4 6 3
4 5 8 3 2 6 9 7 1
1 6 3 7 4 9 5 8 2

输出样例:

1
0
0

代码长度限制:16 KB

Java (javac)

时间限制:500 ms

内存限制:256 MB

其他编译器

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
int main()
{
int a[9][9]={0},i,j,k,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<9;j++)
{
for(k=0;k<9;k++)
{
scanf("%d",&a[j][k]);
}
}
int i2,j2,f=1,l=0;
int c[1000]={0};
for(i2=0;i2<9;i2++)
{
for(j2=0;j2<9;j2++)
{
c[a[i2][j2]]=1;
}
for(j2=1;j2<=9;j2++)
{
if(c[j2]!=1)
{
f=0;
break;
}
}
if(f==0)
break;
}
int d[1000]={0};
for(i2=0;i2<9;i2++)
{
for(j2=0;j2<9;j2++)
{
d[a[j2][i2]]=1;
}
for(j2=1;j2<=9;j2++)
{
if(d[j2]!=1)
{
f=0;
break;
}
}
if(f==0)
break;
}
int x=0,y=2;
int m=0,n=2;
for(int k1=0;k1<9;k1++)
{
int b[1000]={0};
for(int i1=x;i1<=y;i1++)
{
for(int j1=m;j1<=n;j1++)
{
b[a[i1][j1]]=1;
}
}
for(int i2=1;i2<=9;i2++)
{
if(b[i2]!=1)
{
f=0;
break;
}
}

m=(m+3)%9;
n=m+2;
if(m==0)
{
x=x+3;
y=x+2;
}
}
if(f==0)
printf("0\n");
else
printf("1\n");
}
return 0;
}

L2-1 鱼与熊掌

数据结构-L2-1

作者 陈越

单位 浙江大学

《孟子 · 告子上》有名言:“鱼,我所欲也,熊掌,亦我所欲也;二者不可得兼,舍鱼而取熊掌者也。”但这世界上还是有一些人可以做到鱼与熊掌兼得的。
给定 n 个人对 m 种物品的拥有关系。对其中任意一对物品种类(例如“鱼与熊掌”),请你统计有多少人能够兼得?

输入格式:

输入首先在第一行给出 2 个正整数,分别是:n(≤105)为总人数(所有人从 1 到 n 编号)、m(2≤m≤105)为物品种类的总数(所有物品种类从 1 到 m 编号)。
随后 n 行,第 i 行(1≤i≤n)给出编号为 i 的人所拥有的物品种类清单,格式为:
K M[1] M[2] … M[K]

其中 K(≤103)是该人拥有的物品种类数量,后面的 M[*] 是物品种类的编号。题目保证每个人的物品种类清单中都没有重复给出的种类。
最后是查询信息:首先在一行中给出查询总量 Q(≤100),随后 Q 行,每行给出一对物品种类编号,其间以空格分隔。题目保证物品种类编号都是合法存在的。

输出格式:

对每一次查询,在一行中输出两种物品兼得的人数。

输入样例:

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

输出样例:

2
0
3

代码长度限制:16 KB

Java (javac)

时间限制:500 ms

内存限制:256 MB

其他编译器

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自大学生团体天梯赛(第十三届, 除最后两道)_l1-103 整数的持续性 分数 20 作者 陈越 单位 浙江大学 从任一给定的正整数 n 出-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
set<int> st[N];
int n, m, k, x;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < n; ++i) {
cin >> k;
for (int j = 0; j < k; ++j) {
cin >> x;
st[x].insert(i);
}
}
cin >> n;
while (n--) {
cin >> k >> x;
int sum = 0;
for (auto& xx : st[k]) {
if (st[x].count(xx)) ++sum;
}
cout << sum << "\n";
}
return 0;
}

L2-2 懂蛇语

数据结构-L2-2

作者 陈越

单位 浙江大学

在《一年一度喜剧大赛》第二季中有一部作品叫《警察和我之蛇我其谁》,其中“毒蛇帮”内部用了一种加密语言,称为“蛇语”。蛇语的规则是,在说一句话 A 时,首先提取 A 的每个字的首字母,然后把整句话替换为另一句话 B,B 中每个字的首字母与 A 中提取出的字母依次相同。例如二当家说“九点下班哈”,对应首字母缩写是 JDXBH,他们解释为实际想说的是“京东新百货”……
本题就请你写一个蛇语的自动翻译工具,将输入的蛇语转换为实际要表达的句子。

输入格式:

输入第一行给出一个正整数 N(≤105),为蛇语词典中句子的个数。随后 N 行,每行用汉语拼音给出一句话。每句话由小写英文字母和空格组成,每个字的拼音由不超过 6 个小写英文字母组成,两个字的拼音之间用空格分隔。题目保证每句话总长度不超过 50 个字符,用回车结尾。注意:回车不算句中字符。
随后在一行中给出一个正整数 M(≤103),为查询次数。后面跟 M 行,每行用汉语拼音给出需要查询的一句话,格式同上。

输出格式:

对每一句查询,在一行中输出其对应的句子。如果句子不唯一,则按整句的字母序输出,句子间用 | 分隔。如果查不到,则将输入的句子原样输出。
注意:输出句子时,必须保持句中所有字符不变,包括空格。

输入样例:

8
yong yuan de shen
yong yuan de she
jing dong xin bai huo
she yu wo ye hui shuo yi dian dian
liang wei bu yao chong dong
yi dian dian
ni hui shuo she yu a
yong yuan de sha
7
jiu dian xia ban ha
shao ye wu ya he shui you dian duo
liu wan bu yao ci dao
ni hai shi su yan a
yao diao deng
sha ye ting bu jian
y y d s

输出样例:

jing dong xin bai huo
she yu wo ye hui shuo yi dian dian
liang wei bu yao chong dong
ni hui shuo she yu a
yi dian dian
sha ye ting bu jian
yong yuan de sha|yong yuan de she|yong yuan de shen

代码长度限制:16 KB

Java (javac)

时间限制:500 ms

内存限制:256 MB

其他编译器

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自大学生团体天梯赛(第十三届, 除最后两道)_l1-103 整数的持续性 分数 20 作者 陈越 单位 浙江大学 从任一给定的正整数 n 出-CSDN博客)

#include <bits/stdc++.h> 
using namespace std;
map<string, vector<string>> mp;
int n;
string s, ss;
string f() {
stringstream is(s);
string mid;
while (is >> ss) {
mid += ss[0];
}
return mid;
}
int main(){
cin >> n, getchar();
while (n--) {
getline(cin, s);
auto mid = f();
mp[mid].push_back(s);
}
cin >> n, getchar();
while (n--) {
getline(cin, s);
auto mid = f();
if (mp.count(mid)) {
sort(mp[mid].begin(), mp[mid].end()); 
cout << mp[mid][0];
for (int i = 1; i < mp[mid].size(); ++i) {
cout << "|" << mp[mid][i]; 
}
cout << "\n";
} else cout << s << "\n";
}
return 0;
}

L2-3 满树的遍历

数据结构-L2-3

作者 陈越

单位 浙江大学

一棵“k 阶满树”是指树中所有非叶结点的度都是 k 的树。给定一棵树,你需要判断其是否为 k 阶满树,并输出其前序遍历序列。

注:树中结点的度是其拥有的子树的个数,而树的度是树内各结点的度的最大值。

输入格式:

输入首先在第一行给出一个正整数 n(≤105),是树中结点的个数。于是设所有结点从 1 到 n 编号。
随后 n 行,第 i 行(1≤i≤n)给出第 i 个结点的父结点编号。根结点没有父结点,则对应的父结点编号为 0。题目保证给出的是一棵合法多叉树,只有唯一根结点。

输出格式:

首先在一行中输出该树的度。如果输入的树是 k 阶满树,则加 1 个空格后输出 yes,否则输出 no。最后在第二行输出该树的前序遍历序列,数字间以 1 个空格分隔,行首尾不得有多余空格。
注意:兄弟结点按编号升序访问。

输入样例 1:

7
6
5
5
6
6
0
5

输出样例 1:

3 yes
6 1 4 5 2 3 7

输入样例 2:

7
6
5
5
6
6
0
4

输出样例 2:

3 no
6 1 4 7 5 2 3

代码长度限制:16 KB

Java (javac)

时间限制:500 ms

内存限制:256 MB

其他编译器

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自大学生团体天梯赛(第十三届, 除最后两道)_l1-103 整数的持续性 分数 20 作者 陈越 单位 浙江大学 从任一给定的正整数 n 出-CSDN博客)

#include <bits/stdc++.h> 
using namespace std;
const int N = 1e5 + 5;
vector<int> a[N], res;
int n, x, root, maxx, flag = 1;
void dfs(int x) {
res.push_back(x);
if (a[x].size() == 0) {
return;
}
sort(a[x].begin(), a[x].end());
if (a[x].size() != maxx) {
maxx = max(maxx, (int)a[x].size()), flag = 0;
}
for (auto& xx : a[x]) {
dfs(xx);
}
}
int main(){
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> x;
if (x == 0) root = i;
else {
a[x].push_back(i);
}
}
maxx = a[root].size();
dfs(root);
cout << maxx << " " << (flag ? "yes\n" : "no\n");
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << " \n"[i == res.size() - 1];
}
return 0;
}

L2-4 吉利矩阵

数据结构-L2-4

作者 陈越

单位 浙江大学

所有元素为非负整数,且各行各列的元素和都等于 7 的 3×3 方阵称为“吉利矩阵”,因为这样的矩阵一共有 666 种。
本题就请你统计一下,把 7 换成任何一个 [2,9] 区间内的正整数 L,把矩阵阶数换成任何一个 [2,4] 区间内的正整数 N,满足条件“所有元素为非负整数,且各行各列的元素和都等于 L”的 N×N 方阵一共有多少种?

输入格式:

输入在一行中给出 2 个正整数 L 和 N,意义如题面所述。数字间以空格分隔。

输出格式:

在一行中输出满足题目要求条件的方阵的个数。

输入样例:

7 3

输出样例:

666

代码长度限制:16 KB

时间限制:1000 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自大学生团体天梯赛(第十三届, 除最后两道)_l1-103 整数的持续性 分数 20 作者 陈越 单位 浙江大学 从任一给定的正整数 n 出-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
int main() {
int l, n, res = 0;
cin >> l >> n;
vector<int> check1(n), check2(n);
function<void(int)> dfs = [&](int x) {
if (x == n * n) {
++res;
return;
}
for (int i = 0; i <= l; ++i) {
if (x % n == n - 1 && i != l - check1[x / n]) continue;
if (x / n == n - 1 && i != l - check2[x % n]) continue;
if (check1[x / n] + i <= l && check2[x % n] + i <= l) {
check1[x / n] += i, check2[x % n] += i;
dfs(x + 1);
check1[x / n] -= i, check2[x % n] -= i;
}
}
};
dfs(0);
cout << res;
return 0;
}

五、2024.4.10——23软工树作业1

数据结构-5

(1)函数题

数据结构-5.1

6-1 二分查找

数据结构-6-1

作者 陈越

单位 浙江大学

本题要求实现二分查找算法。

函数接口定义:

Position BinarySearch( List L, ElementType X );

其中List结构定义如下:

typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};

L是用户传入的一个线性表,其中ElementType元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数BinarySearch要查找X在Data中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10
#define NotFound 0
typedef int ElementType;

typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};

List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch( List L, ElementType X );

int main()
{
List L;
ElementType X;
Position P;

L = ReadInput();
scanf("%d", &X);
P = BinarySearch( L, X );
printf("%d\n", P);

return 0;
}

/* 你的代码将被嵌在这里 */

输入样例1:

5
12 31 55 89 101
31

输出样例1:

2

输入样例2:

3
26 78 233
31

输出样例2:

0

鸣谢宁波大学 Eyre-lemon-郎俊杰 同学修正原题!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Position BinarySearch( List L, ElementType X )
{
Position right=L->Last,left=1,mid;
while(left<=right)
{
mid=(left+right)/2;
if(X<L->Data[mid])
{right=mid-1;}
else if(X>L->Data[mid])
{left=mid+1;}
else if(X==L->Data[mid])
{return mid;}
}
return NotFound;
}

6-2 先序输出叶结点

数据结构-6-2

作者 陈越

单位 浙江大学

本题要求按照先序遍历的顺序输出给定二叉树的叶结点。

函数接口定义:

void PreorderPrintLeaves( BinTree BT );

其中BinTree结构定义如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

函数PreorderPrintLeaves应按照先序遍历的顺序输出给定二叉树BT的叶结点,格式为一个空格跟着一个字符。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
void PreorderPrintLeaves( BinTree BT );

int main()
{
BinTree BT = CreatBinTree();
printf("Leaf nodes are:");
PreorderPrintLeaves(BT);
printf("\n");

return 0;
}
/* 你的代码将被嵌在这里 */

输出样例(对于图中给出的树):

Leaf nodes are: D E H I

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void PreorderPrintLeaves( BinTree BT )
{
if(BT)
{
if(!BT->Left&&!BT->Right)
printf(" %c",BT->Data);
PreorderPrintLeaves(BT->Left);
PreorderPrintLeaves(BT->Right);
}
}

6-3 求二叉树高度

数据结构-6-3

作者 陈越

单位 浙江大学

本题要求按照先序遍历的顺序输出给定二叉树的叶结点。

函数接口定义:

void PreorderPrintLeaves( BinTree BT );

其中BinTree结构定义如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

函数PreorderPrintLeaves应按照先序遍历的顺序输出给定二叉树BT的叶结点,格式为一个空格跟着一个字符。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
void PreorderPrintLeaves( BinTree BT );

int main()
{
BinTree BT = CreatBinTree();
printf("Leaf nodes are:");
PreorderPrintLeaves(BT);
printf("\n");

return 0;
}
/* 你的代码将被嵌在这里 */

输出样例(对于图中给出的树):

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int GetHeight( BinTree BT )
{
int HL,HR,MaxH;
if(BT)
{
HL=GetHeight(BT->Left);
HR=GetHeight(BT->Right);
MaxH=HL>HR?HL:HR;
return (MaxH+1);
}
else return 0;
}

6-4 二叉树的遍历

数据结构-6-4

作者 陈越

单位 浙江大学

本题要求给定二叉树的4种遍历。

函数接口定义:

void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );

其中BinTree结构定义如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

要求4个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。

测试程序样例:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );

int main()
{
BinTree BT = CreatBinTree();
printf("Inorder:"); InorderTraversal(BT); printf("\n");
printf("Preorder:"); PreorderTraversal(BT); printf("\n");
printf("Postorder:"); PostorderTraversal(BT); printf("\n");
printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */

输出样例(对于图中给出的树):

Inorder: D B E F A G H C I
Preorder: A B D F E C G H I
Postorder: D E F B H G I C A
Levelorder: A B C D F G I E H

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void PreorderPrintLeaves( BinTree BT )
{
if(BT)
{
if(!BT->Left&&!BT->Right)
printf(" %c",BT->Data);
PreorderPrintLeaves(BT->Left);
PreorderPrintLeaves(BT->Right);
}
}

6-5 二叉树的非递归遍历

数据结构-6-5

作者 陈越

单位 浙江大学

本题要求用非递归的方法实现对给定二叉树的 3 种遍历。

函数接口定义:

void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );

其中BinTree结构定义如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
int flag;
};

要求 3 个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。

此外,裁判程序中给出了堆栈的全套操作,可以直接调用。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
typedef enum { false, true } bool;

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
int flag;
};

/*------堆栈的定义-------*/
typedef Position SElementType;
typedef struct SNode *PtrToSNode;
struct SNode {
SElementType Data;
PtrToSNode Next;
};
typedef PtrToSNode Stack;

/* 裁判实现,细节不表 */
Stack CreateStack();
bool IsEmpty( Stack S );
bool Push( Stack S, SElementType X );
SElementType Pop( Stack S ); /* 删除并仅返回S的栈顶元素 */
SElementType Peek( Stack S );/* 仅返回S的栈顶元素 */
/*----堆栈的定义结束-----*/

BinTree CreateBinTree(); /* 裁判实现,细节不表 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );

int main()
{
BinTree BT = CreateBinTree();
printf("Inorder:"); InorderTraversal(BT); printf("\n");
printf("Preorder:"); PreorderTraversal(BT); printf("\n");
printf("Postorder:"); PostorderTraversal(BT); printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */

输入样例:

如图

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void InorderTraversal( BinTree BT ){
BinTree T;
Stack S=CreateStack();
T=BT;
while(T|| !IsEmpty(S)){
while(T){
Push(S, T);
T = T->Left;
}
T=Pop(S);
printf(" %c",T->Data);
T=T->Right;
}
}
void PreorderTraversal( BinTree BT ){
BinTree T;
Stack S=CreateStack();
T=BT;
while(T|| !IsEmpty(S)){
while(T){
Push(S, T);
printf(" %c",T->Data);
T=T->Left;
}
T=Pop(S);
T=T->Right;
}
}
void PostorderTraversal( BinTree BT )
{
BinTree T;
Stack S=CreateStack();
T=BT;
while(T||!IsEmpty(S))
{
while(T){
Push(S,T);
T=T->Left;
}
T=Peek(S);
if (T->flag!= 1)
{
T->flag= 1;
T=T->Right;
}
else {
T=Pop(S);
printf(" %c",T->Data);
T=NULL;
}
}
}

(2)编程题

数据结构-5.2

7-1 还原二叉树

数据结构-7-1

作者 DS课程组

单位 浙江大学

给定一棵二叉树的前序遍历序列和中序遍历序列,要求计算该二叉树的高度。

输入格式:

输入首先给出正整数 n(≤50),为树中结点总数。随后 2 行先后给出前序和中序遍历序列,均是长度为 n 的不包含重复英文字母(区别大小写)的字符串。

输出格式:

输出为一个整数,即该二叉树的高度。

输入样例:

9
ABDFGHIEC
FDHGIBEAC

输出样例:

5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-1 还原二叉树 (25分) AC代码-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
struct btnode {
char value;
btnode *lc;
btnode *rc;
};
char pre[55];
char pos[55];
int n;
int ans=0;
btnode* buildtree(char pre[],char pos[],int n,int cnt)
{
if(n==0) return NULL;

btnode *F=new btnode;
int root=pre[0];
F->value=root;

int k=0;
for(int i=0;i<n;i++)
{
if(pos[i]==root)
{
k=i;
break;
}
}
cnt++;
F->lc=buildtree(pre+1,pos,k,cnt);
if(F->lc){
ans=max(cnt,ans);
}
F->rc=buildtree(pre+k+1,pos+k+1,n-k-1,cnt);
if(F->rc){
ans=max(cnt,ans);
}

return F;
}

int main()
{
cin>>n;
cin>>pre;
cin>>pos;
// cout<<ans;

btnode *F=buildtree(pre,pos,n,1);
if(n==1) ans=1;
cout<<ans;
return 0;
}

7-2 树的遍历

数据结构-7-2

作者 陈越

单位 浙江大学

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

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

输出样例:

4 1 6 3 5 7 2

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-2 树的遍历 (PTA-数据结构)_树的遍历pta-CSDN博客)

//
// Created by DDD on 2023/11/20.
//
#include <stdio.h>
#include <malloc.h>

typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;

TreeNode* buildTree(int min[], int post[], int n){
if(!n)
return NULL;
TreeNode *T = (TreeNode *)malloc(sizeof(struct TreeNode));
T->val = post[n-1]; //后序遍历的最后一个节点就是树的根节点
T->left = T->right = NULL;

//从中序遍历中找到根节点的位置
int index;
for(index=0; index<n; index++)
{
if(min[index] == post[n-1]) break;
}
T->left = buildTree(min, post, index);
T->right = buildTree(min+index+1, post+index, n-index-1);
return T;

}


void LevelOrder(TreeNode *T)
{
if(T)
{
TreeNode *queue[100];
int left = 0, right = 0;
queue[right++] = T;
while (left < right)
{
TreeNode *bt = queue[left++];
if(bt == T)
printf("%d", bt->val); //为根节点时,无空格输出
else
printf(" %d", bt->val);
if(bt->left)
queue[right++] = bt->left;
if(bt->right)
queue[right++] = bt->right;
}
}
}


int main(){
int num;
scanf("%d",&num);
int post[100]; //后序
int min[100]; //中序
//int Tree[1000] = {0}; //先序
for(int i=0; i<num;i++){
scanf("%d",&post[i]);
}
for(int i=0; i<num;i++){
scanf("%d",&min[i]);
}
//makePre(Tree,post,min,num - 1,num,0);
TreeNode TN = *buildTree(min,post,num);
LevelOrder(&TN);
}

7-3 完全二叉树的层序遍历

数据结构-7-3

作者 陈越

单位 浙江大学

一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树。

给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。

输入格式:

输入在第一行中给出正整数 N(≤30),即树中结点个数。第二行给出后序遍历序列,为 N 个不超过 100 的正整数。同一行中所有数字都以空格分隔。

输出格式:

在一行中输出该树的层序遍历序列。所有数字都以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
91 71 2 34 10 15 55 18

输出样例:

18 34 55 71 2 10 15 91

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-3 完全二叉树的层序遍历-CSDN博客)

#include <iostream>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 1e5 + 5;

int n;
int tree[N];

void build(int x) {
int l = x * 2, r = x * 2 + 1;
if (l <= n) build(l);
if (r <= n) build(r);
cin >> tree[x];
}

void solve() {
cin >> n;
build(1);
for (int i = 1; i <= n; i++) cout << tree[i] << " \n"[i == n];
}

int main() {

int T;
// cin >> T;while(T--)solve();

solve();

return 0;
}

7-4 玩转二叉树

数据结构-7-3

作者 陈越

单位 浙江大学

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

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

输出样例:

4 6 1 7 5 3 2

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自数据结构与算法实验5——树和二叉树 7-4 玩转二叉树_7-4 插松枝 分数 25-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;

int n; // 节点数
int pre[N]; // 先序遍历得到的的序列
int mid[N]; // 中序遍历得到的的序列

struct node
{
int data; //节点的数据
node *l, *r; //左孩子,右孩子
};

node *build(int len, int *pre, int *mid) //建树
{
node *root = new node;
if (!len)
return NULL; // 返回空节点
root->data = pre[0]; // pre[0]为根节点
int i;
for (i = 0; i < len; i++)
{
if (mid[i] == pre[0]) // 在中序遍历中找到根节点
break;
}
root->l = build(i, pre + 1, mid); // 建立左子树
root->r = build(len - i - 1, pre + i + 1, mid + i + 1); // 建立右子树
return root;
}

void cengxu(node *root)//层序遍历,从右往左遍历
{
bool flag = 0;
queue<node *> q;
q.push(root);
while (q.size())
{
node *top = q.front();
if (flag)
cout << " " << top->data;
else
{
cout << top->data;
flag = 1;
}
q.pop();
//先放右孩子,再放左孩子
if (top->r)
q.push(top->r);
if (top->l)
q.push(top->l);
}
}

int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> mid[i];
for (int i = 0; i < n; i++)
cin >> pre[i];
node *root = build(n, pre, mid);
cengxu(root);
return 0;
}

四、2024.3.31——23软工作业栈和队列

数据结构-4

(1)函数题

数据结构-4.1

6-1 在一个数组中实现两个堆栈

数据结构-6-1

作者 陈越

单位 浙江大学

本题要求在一个数组中实现两个堆栈。

函数接口定义:

Stack CreateStack( int MaxSize );
bool Push( Stack S, ElementType X, int Tag );
ElementType Pop( Stack S, int Tag );

其中Tag是堆栈编号,取1或2;MaxSize堆栈数组的规模;Stack结构定义如下:

typedef int Position;
struct SNode {
ElementType *Data;
Position Top1, Top2;
int MaxSize;
};
typedef struct SNode *Stack;

注意:如果堆栈已满,Push函数必须输出“Stack Full”并且返回false;如果某堆栈是空的,则Pop函数必须输出“Stack Tag Empty”(其中Tag是该堆栈的编号),并且返回ERROR。

裁判测试程序样例:

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;

int n; // 节点数
int pre[N]; // 先序遍历得到的的序列
int mid[N]; // 中序遍历得到的的序列

struct node
{
int data; //节点的数据
node *l, *r; //左孩子,右孩子
};

node *build(int len, int *pre, int *mid) //建树
{
node *root = new node;
if (!len)
return NULL; // 返回空节点
root->data = pre[0]; // pre[0]为根节点
int i;
for (i = 0; i < len; i++)
{
if (mid[i] == pre[0]) // 在中序遍历中找到根节点
break;
}
root->l = build(i, pre + 1, mid); // 建立左子树
root->r = build(len - i - 1, pre + i + 1, mid + i + 1); // 建立右子树
return root;
}

void cengxu(node *root)//层序遍历,从右往左遍历
{
bool flag = 0;
queue<node *> q;
q.push(root);
while (q.size())
{
node *top = q.front();
if (flag)
cout << " " << top->data;
else
{
cout << top->data;
flag = 1;
}
q.pop();
//先放右孩子,再放左孩子
if (top->r)
q.push(top->r);
if (top->l)
q.push(top->l);
}
}

int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> mid[i];
for (int i = 0; i < n; i++)
cin >> pre[i];
node *root = build(n, pre, mid);
cengxu(root);
return 0;
}

输入样例:

5
Push 1 1
Pop 2
Push 2 11
Push 1 2
Push 2 12
Pop 1
Push 2 13
Push 2 14
Push 1 3
Pop 2
End

输出样例:

Stack 2 Empty
Stack 2 is Empty!
Stack Full
Stack 1 is Full!
Pop from Stack 1: 1
Pop from Stack 2: 13 12 11

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Stack CreateStack( int MaxSize )
{
Stack S;
S=(Stack)malloc(sizeof(struct SNode));
S->Data=(ElementType *)malloc(sizeof(ElementType)*MaxSize);
S->MaxSize=MaxSize;
S->Top1=-1;
S->Top2=S->MaxSize;
return S;
}
bool Push( Stack S, ElementType X, int Tag )
{
if(S->Top2-S->Top1==1)
{
printf("Stack Full\n");
return false;
}
if(Tag==1)
{
S->Data[++(S->Top1)]=X;
}
else
{
S->Data[--(S->Top2)]=X;
}
return true;
}
ElementType Pop( Stack S, int Tag )
{
if(Tag==1)
{
if(S->Top1==-1)
{
printf("Stack 1 Empty\n");
return ERROR;
}
return S->Data[(S->Top1)--];
}
else
{
if(S->Top2==S->MaxSize)
{
printf("Stack 2 Empty\n");
return ERROR;
}
return S->Data[(S->Top2)++];
}
}

6-2 另类堆栈

数据结构-6-2

作者 DS课程组

单位 浙江大学

在栈的顺序存储实现中,另有一种方法是将Top定义为栈顶的上一个位置。请编写程序实现这种定义下堆栈的入栈、出栈操作。如何判断堆栈为空或者满?

函数接口定义:

bool Push( Stack S, ElementType X );
ElementType Pop( Stack S );

其中Stack结构定义如下:

typedef int Position;
typedef struct SNode *PtrToSNode;
struct SNode {
ElementType *Data; /* 存储元素的数组 */
Position Top; /* 栈顶指针 */
int MaxSize; /* 堆栈最大容量 */
};
typedef PtrToSNode Stack;

注意:如果堆栈已满,Push函数必须输出“Stack Full”并且返回false;如果队列是空的,则Pop函数必须输出“Stack Empty”,并且返回ERROR。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

#define ERROR -1
typedef int ElementType;
typedef enum { push, pop, end } Operation;
typedef enum { false, true } bool;
typedef int Position;
typedef struct SNode *PtrToSNode;
struct SNode {
ElementType *Data; /* 存储元素的数组 */
Position Top; /* 栈顶指针 */
int MaxSize; /* 堆栈最大容量 */
};
typedef PtrToSNode Stack;

Stack CreateStack( int MaxSize )
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
S->Top = 0;
S->MaxSize = MaxSize;
return S;
}

bool Push( Stack S, ElementType X );
ElementType Pop( Stack S );

Operation GetOp(); /* 裁判实现,细节不表 */
void PrintStack( Stack S ); /* 裁判实现,细节不表 */

int main()
{
ElementType X;
Stack S;
int N, done = 0;

scanf("%d", &N);
S = CreateStack(N);
while ( !done ) {
switch( GetOp() ) {
case push:
scanf("%d", &X);
Push(S, X);
break;
case pop:
X = Pop(S);
if ( X!=ERROR ) printf("%d is out\n", X);
break;
case end:
PrintStack(S);
done = 1;
break;
}
}
return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

4
Pop
Push 5
Push 4
Push 3
Pop
Pop
Push 2
Push 1
Push 0
Push 10
End

输出样例:

Stack Empty
3 is out
4 is out
Stack Full
0 1 2 5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

bool Push( Stack S, ElementType X )
{
if(S->Top==S->MaxSize)
{
printf("Stack Full\n");
return false;
}
else
{
S->Data[S->Top]=X;
S->Top++;
return true;
}
}
ElementType Pop( Stack S )
{
if(S->Top==0)
{
printf("Stack Empty\n");
return ERROR;
}
else
{
S->Top--;
return S->Data[S->Top];
}
}

(2)编程题

数据结构-4.2

7-1 队列的实现及基本操作

数据结构-7-1

作者 朱允刚

单位 吉林大学

给定一个初始为空的队列和一系列入队、出队操作,请编写程序输出每次出队的元素。队列的元素值均为整数。

输入格式:

输入第1行为1个正整数n,表示操作个数;接下来n行,每行表示一个操作,格式为1 d或0。1 d表示将整数d入队,0表示出队。n不超过20000。

输出格式:

按顺序输出每次出队的元素,每个元素一行。若某出队操作不合法(如在队列空时出队),则对该操作输出invalid。

输入样例:

7
1 1
1 2
0
0
0
1 3
0

输出样例:

1
2
invalid
3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[30000];
int r=0,l=0;
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int x;
scanf("%d",&x);
if(x==1)
{
scanf("%d",&a[r++]);
}
else
{
if(l<r)
{
printf("%d\n",a[l++]);
}
else
printf("invalid\n");
}
}
return 0;
}

7-2 队的基本操作

数据结构-7-2

作者 唐艳琴

单位 中国人民解放军陆军工程大学

给定一个初始为空的队(队存储空间长度为10)和一系列进队、出队操作,请编写程序输出经过这些操作后队中的元素。队中元素值均为整数。(采用循环队列完成,禁用一个空间方法)

输入格式:

输入第1行为1个正整数n,表示操作个数;

第2行为给出的n个整数,非0元素表示进队,且此非0值即为进队元素,0元素表示出队。

输出格式:

第一行按出队顺序输出所有出队元素,以一个空格隔开;如果队空时做出队操作会输出”EMPTY”,如果队满时做进队操作会输出”FULL”。

第二行中输出队中所有元素,以一个空格隔开。

末尾均有一个空格。

输入样例:

12
3 1 2 0 0 -1 0 0 0 4 5 0

输出样例:

3 1 2 -1 EMPTY 4 
5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include<stdio.h>
#include<stdlib.h>

struct Queue{
int data;
struct Queue* next;
}*queue;

struct Queue *createQueue();
void push(int num);
void pop();
int main()
{
queue = createQueue();
int N,num;
scanf("%d",&N);
for(int z=0;z<N;z++){
scanf("%d",&num);
if(num==0) pop();
else push(num);
}
putchar('\n');
while (queue->data!=0){
printf("%d ",queue->data);
queue->data = 0;
queue = queue->next;
}
return 0;
}

struct Queue *createQueue()
{
struct Queue *head,*body;
head = (struct Queue *) malloc(sizeof(struct Queue));
head->data = 0; // 0 默认空数据
body = head;
for(int z=1;z<10;z++){
body->next = (struct Queue *) malloc(sizeof(struct Queue));
body = body->next;
body->data = 0;
}
body->next = head;
return head;
}

void push(int num)
{
struct Queue *head = queue;
for(int z=0;z<9;z++){
if(head->data==0){
head->data = num;
return;
}
head = head->next;
}
printf("FULL ");
}

void pop()
{
if(queue->data==0) printf("EMPTY ");
else
{
printf("%d ",queue->data);
queue->data = 0;
queue = queue->next;
}
}

7-3 有趣的括号

数据结构-7-3

作者 Drizzle

单位 山东科技大学

括号()的组合千奇百怪,Drizzle 想知道各种组合的括号可以是否合法
合法要求:每个同类型的左括号必须有与之对应的同类的右括号以正确的顺序闭合

要求:

输入:输入一个括号字符串
输出:输出是否合法,是则True,否则False

示例:

输入:

(){}[]

输出:

True

范围:

对于 100% 的数据:括号字符串长度 ≤ 100

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[200],b[200];
int i,x=0,y=0,j,f=1;
gets(a);
for(i=0,j=-1;a[i];i++)
if(a[i]=='('||a[i]=='{'||a[i]=='[')
b[++j]=a[i];
else if(a[i]==')')
{
if(j>=0&&b[j]=='(')
j--;
else f=0;
}
else if(a[i]=='}')
{
if(j>=0&&b[j]=='{')
j--;
else f=0;
}
else if(a[i]==']')
{
if(j>=0&&b[j]=='[')
j--;
else f=0;
}
if(j>=0)
f=0;
if(f) printf("True");
else printf("False");

return 0;
}

三、2024.3.31——23软1数据结构实验二

数据结构-3

(1)编程题

数据结构-3.1

7-1 栈操作的合法性

7-1

作者 DS课程组

单位 浙江大学

假设以S和X分别表示入栈和出栈操作。如果根据一个仅由S和X构成的序列,对一个空堆栈进行操作,相应操作均可行(如没有出现删除时栈空)且最后状态也是栈空,则称该序列是合法的堆栈操作序列。请编写程序,输入S和X序列,判断该序列是否合法。

输入格式:

输入第一行给出两个正整数 n 和 m,其中 n 是待测序列的个数,m(≤50)是堆栈的最大容量。随后 n 行,每行中给出一个仅由S和X构成的序列。序列保证不为空,且长度不超过100。

输出格式:

对每个序列,在一行中输出YES如果该序列是合法的堆栈操作序列,或NO如果不是。

输入样例:

4 10
SSSXXSXXSX
SSSXXSXXS
SSSSSSSSSSXSSXXXXXXXXXXX
SSSXXSXXX

输出样例:

YES
NO
NO
NO

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,m;
scanf("%d%d",&n,&m);
getchar();
int cnt=0,i,j;
char s[200];
for(i=0;i<n;i++)
{
cnt=0;
gets(s);
for(j=0;s[j];j++)
{
if(s[j]=='S')
{
if(cnt<m) cnt++;
else break;
}
else
{
if(cnt>0) cnt--;
else break;
}
}
if(s[j]==0&&cnt==0) printf("YES\n");
else printf("NO\n");
}
return 0;
}

7-2 符号配对

7-2

作者 DS课程组

单位 浙江大学

请编写程序检查C语言源程序中下列符号是否配对:/*与*/、(与)、[与]、{与}。

输入格式:

输入为一个C语言源程序。当读到某一行中只有一个句点.和一个回车的时候,标志着输入结束。程序中需要检查配对的符号不超过100个。

输出格式:

首先,如果所有符号配对正确,则在第一行中输出YES,否则输出NO。然后在第二行中指出第一个不配对的符号:如果缺少左符号,则输出?-右符号;如果缺少右符号,则输出左符号-?。

输入样例1:

void test()
{
int i, A[10];
for (i=0; i<10; i++) { /*/
A[i] = i;
}
.

输出样例1:

NO
/*-?

输入样例2:

void test()
{
int i, A[10];
for (i=0; i<10; i++) /**/
A[i] = i;
}]
.

输出样例2:

NO
?-]

输入样例3:

void test()
{
int i
double A[10];
for (i=0; i<10; i++) /**/
A[i] = 0.1*i;
}
.

输出样例3:

YES

鸣谢用户 王渊博 补充数据!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-2 符号配对 (20 分) c语言版-CSDN博客)

#include <stdio.h>
#include <stdlib.h>
#define Maxsize 105

typedef struct StackRecord *Stack;
struct StackRecord {
int Top;
char *Array;
};

Stack creat(){
Stack s = (Stack) malloc(sizeof(struct StackRecord));
s->Array = (char *) malloc(Maxsize * sizeof(char));
s->Top = -1;
return s;
}

int is_empty(Stack s){
if(s->Top == -1) return 1;
else return 0;
}
void push(Stack s, char x){
s->Array[++(s->Top)] = x;
}
void pop(Stack s){
s->Top--;

}
char top(Stack s){
return s->Array[s->Top];
}
char a[100];
char str[200];
int main(){
int k = 0;
char t;
while(gets(str)){

if(str[0]=='.'&&!str[1]) break;
for(int i=0; str[i]; i++){
if(str[i]=='('||str[i]=='['||str[i]=='{'||str[i]==')'||str[i]=='}' ||str[i]==']')
a[k++]=str[i];
else if(str[i]=='/'&&str[i+1]=='*'){
a[k++]='<';
i++;
}else if(str[i]=='*'&&str[i+1]=='/'){
a[k++]='>';
i++;
}
}
}
int flag=0;
Stack s = creat();
for(int i=0; i<k; i++){
if(a[i]=='(' || a[i]=='[' || a[i]=='{' || a[i]=='<') {
push(s, a[i]);
} else if(a[i] == ')'){
if(s->Top!=-1 && top(s)=='(') pop(s);
else{
t = a[i];
flag = 1;
break;
}

} else if(a[i] == ']'){
if(s->Top != -1 && top(s)=='[') pop(s);
else{
t = a[i];
flag = 1;
break;
}

} else if(a[i] == '}'){
if(s->Top != -1 && top(s)== '{') pop(s);
else{
t = a[i];
flag = 1;
break;
}
} else if(a[i] == '>'){
if(s->Top != -1 && top(s)== '<') pop(s);
else{
t = a[i];
flag = 1;
break;
}
}
}
if(!flag && is_empty(s)) printf("YES\n");
else{
printf("NO\n");
if(!is_empty(s)){
if(top(s)=='<') printf("/*-?\n");
else printf("%c-?\n", top(s));
}else{
if(t=='>') printf("?-*/\n");
else printf("?-%c\n", t);
}
}
return 0;
}

7-3 后缀式求值(一位整型操作数版)

7-3

作者 周强

单位 青岛大学

我们人类习惯于书写“中缀式”,如 3 + 5 * 2 ,其值为13。 (p.s. 为什么人类习惯中缀式呢?是因为中缀式比后缀式好用么?)

而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是: 3 5 2 * +

现在,请对输入的后缀式进行求值。为了简化输入处理和运算,运算数(操作数)不超过300个且均为1位正整数,运算符(操作符)仅有+ - * /(加减乘除)四种,运算数和运算符之间没有空格间隔,且题目保证运算的中间结果和最终结果都在整型范围内。

但是注意,题目输入的后缀式可能错误,例如:

  • 1234+- 错误,缺少运算符
  • 123+-* 错误,缺少运算数
  • 122-/ 错误,除数为0

题目保证以上三种错误不会同时发生。

输入格式:

第一行给出一个不超过10的正整数k;

接下来k行,每行给出一个后缀式,后缀式的格式如上文所描述,1位操作数且无空格间隔。

输出格式:

输出有k行,对于所输入的每个后缀式,判断是否正确(可求值),并在一行里输出:

  • 如果后缀式无误、可求值,输出结果
  • 如果发现除数为0,则输出Division By Zero!
  • 如果发现其它错误,则输出Expression Error!

输入样例1:

2
1234+-*
123+4-*

输出样例1:

-5
1

输入样例2:

2
12+
1234+-

输出样例2:

3
Expression Error!

输入样例3:

2
2222+-*
22+-*

输出样例3:

-4
Expression Error!

输入样例4:

1
2222-/+

输出样例4:

Division By Zero!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include<bits/stdc++.h>
using namespace std;

stack<int> ans;

int main()
{
int n;
cin >> n;
while(n --)
{
string s;
cin >> s;

int num = 0, way = 0;
bool flag = 0;

for(int i = 0; i < s.size(); i ++)
{
if(s[i] >= '0' && s[i] <= '9')
{
num ++;
}
if(s[i] == '+' || s[i]== '-' ||s[i] == '*' || s[i] == '/')
{
way ++;
}
}

if(num - way != 1)
{
cout << "Expression Error!" << endl;
continue;
}

for(int i = 0; i < s.size(); i ++)
{
if (s[i] >= '0' && s[i] <= '9')
{
ans.push(s[i] - '0');
}

if (s[i] == '+')
{
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(a + b);
}

else if (s[i] == '-')
{
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(b - a);
}

else if (s[i] == '*')
{
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(b * a);
}

else if (s[i] == '/')
{
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
if (a)
{
ans.push(b / a);
}
else
{
cout << "Division By Zero!" << endl;
flag = 1;
break;
}
}
}

if (flag)
{
continue;
}

cout << ans.top() << endl;
}

return 0;
}

7-4 中缀表达式转换为后缀表达式并求值

7-4

作者 伍建全

单位 重庆科技大学

把题目给出中缀表达式转换为后缀表达式输出,并求后缀表达式的值。为简单起见,我们约定:1、输入的中缀表达式一定是合法的,并且只含数字,四种运算符+、-、*、/和小括号;2、运算数都是一位正整数(1~9);3、输入的中缀表达式不超过20个字符;4、除法运算的结果仍然是正整数。

输入格式:

输入的第一行是一个正整数 N ,表示以下有 N 行。每行是一个中缀表达式。为简单起见,我们约定:1、输入的中缀表达式一定是合法的,并且只含数字,四种运算符+、-、*、/和小括号;2、运算数都是一位正整数(1~9);3、输入的中缀表达式不超过20个字符;4、除法运算的结果仍然是正整数。

输出格式:

输出每行中缀表达式所对应后缀表达式,隔一个空格之后,输出该后缀表达式计算之后得到的值。

输入样例:

在这里给出一组输入。例如:

6
2+4
3+2*7
2*(4+6)
(5/2+4)*5+2
(3+5)*(7-2)/4
5*(8-(3+2))

输出样例:

在这里给出相应的输出。例如:

24+ 6
327*+ 17
246+* 20
52/4+5*2+ 32
35+72-*4/ 10
5832+-* 15**
3
Expression Error!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自7-3 中缀表达式转换为后缀表达式并求值 (20分)数据结构实验3羊卓的杨_把题目给出中缀表达式转换为后缀表达式输出,并求后缀表达式的值。为简单起见,我们-CSDN博客)

#include <bits/stdc++.h>
using namespace std;
char suffix[22];//存放后缀表达式
stack <char> trans;//转换栈
stack <int> jisuan;//计算栈
string str;
int N;

int caculate(int x, int y, char z){//求值要用到的运算函数
switch(z){
case '-': return y-x;//注意这里的顺序
case '+': return x+y;
case '*': return x*y;
case '/': return y/x;//注意这里的顺序
}
}

bool op(char a, char b){//如果a优先级高于b就返回true
if((b =='+' || b == '-') && (a == '*' || a == '/'))
return true;
if((b =='*' || b == '/') && (a == '*' || a == '/'))//其实可以不写,只不过更好理解
return false;
return false;
}

bool isop(char a){//检验字符是否为运算符
if(a=='-' || a=='+' || a=='*' || a=='/')
return true;
return false;
}

void get_suffix(){//获取后缀表达式
int i=0, j=0;
while(str[i] != '\0'){
if(isdigit(str[i])) suffix[j++] = str[i];
else if(str[i] == '(') trans.push(str[i]);
else if(str[i] == ')'){
while(trans.top() != '('){
suffix[j++] = trans.top();
trans.pop();
}
trans.pop();
}
else if(isop(str[i])){
if(trans.empty() || trans.top()=='(' || op(str[i],trans.top()))
trans.push(str[i]);
else if(!op(str[i],trans.top())){
while((trans.top()!='(') && !op(str[i], trans.top()) && !trans.empty()){//要特别注意这里的判断条件
suffix[j++] = trans.top();
trans.pop();
if(trans.empty())
break;
}
trans.push(str[i]);
}
}
i++;
}
while(!trans.empty()){
suffix[j++] = trans.top();
trans.pop();
}
cout << suffix << " ";//输出答案
}

void suffix_ans(){
int i=0, ans=0;
while(suffix[i] != '\0'){
if(isdigit(suffix[i]))
jisuan.push(suffix[i]-'0');
else{
int x = jisuan.top();
jisuan.pop();
int y = jisuan.top();
jisuan.pop();
ans = caculate(x, y, suffix[i]);
jisuan.push(ans);
}
i++;
}
cout << ans << endl;
jisuan.pop();
}

int main(){
cin >> N;
while(N--){
memset(suffix, '\0', sizeof(suffix));
str = "\0";
cin >> str;
get_suffix();
suffix_ans();
}
return 0;
}

7-5 令人抓狂的四则运算

7-5

作者 周强

单位 青岛大学

曾记否,我们小学时,遇到这种四则运算,心情是抓狂的:

四则运算.png 抓狂.jpg

那么当我们学会使用计算机,自然是要程序去完成这个工作啦~ 现在请对输入的四则运算求值。注意:

  • 四则运算表达式必定包含运算数,还可能包含运算符和括号( ),不含空格等其它字符
  • 运算数必定包含数字,还可能包含正或负符号+、-以及小数点.
  • 运算符仅有+(加)、-(减)、*(乘以)、/(除以)四种
  • 括号可以嵌套
  • 对于带符号的数,可以加括号,也可以不加括号,例如:1+-2*+3和1+(-2)*(+3)是等价的
  • 括号内可以是包含运算符的表达式,也可以仅有运算数,例如:1*(2)和1*(2+3)都是合法的表达式

输入格式:

输入由若干行组成:

  • 除最后一行之外,每一行是一个长度不超过80的四则运算表达式
  • 最后一行,是一个=字符

输入的所有字符均为英文半角字符,题目保证给定的表达式是正确的,不需要做有效性检查,题目保证所有运算数的长度(含小数点)均不超过5位,运算的中间结果和最终结果的绝对值均不超过100000

输出格式:

对输入的每个表达式,在一行中给出运算结果,保留1位小数。

输入样例:

1
1+2
3-3.8
1.32*(4+(-2))
=

输出样例:

1.0
3.0
-0.8
2.6

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自令人抓狂的四则运算pta c语言_令人抓狂的四则运算算法思路-CSDN博客)

#include <stdio.h>
#include <string.h>

char s[100];
double stk_num[100];
char stk_fu[100];

int is_number(char c)
{
return c >= '0' && c <= '9' || c == '.';
}

int check(char a, char b)
{
if(a == '+' || a == '-')
{
if(b == '+' || b == '-')return 0;
else return 1;
}
else if(a == '*' || a == '/')
{
if(b == '(')return 1;
else return 0;
}
else if(a == '(')
{
if(b == ')')return 0;
else return 1;
}
}

double fun(double a, char c, double b)
{
if(c == '-')return b - a;
if(c == '+')return b + a;
if(c == '*')return b * a;
if(c == '/')return b / a;
}

int main()
{
int len;
int top_num;
int top_fu;
while(1)
{
scanf("%s", s);
if(s[0] == '=')break;
len = strlen(s);
top_num = 0, top_fu = 0;
for(int i = 0; i < len; i++)
{
// printf("i = %d top_num = %d top_fu = %d\n", i, top_num, top_fu);
// for(int m = 1; m <= top_num; m++)printf("%f ",stk_num[m]);
// printf("\n");
// for(int m = 1; m <= top_fu; m++)printf("%c ", stk_fu[m]);
// printf("\n");
//处理数字部分
if(is_number(s[i]))
{
double number = 0;

int j, k;
for(j = i; j < len && s[j] != '.' && is_number(s[j]) != 0; j++)
number = number * 10 + s[j] - '0';

k = j;

if(s[j] =='.')
{
double m = 0.1;
for(k = j + 1; k < len && is_number(s[k]) != 0; k++)
{
number += m * (s[k] - '0');
m /= 10;
}
}
if(i == 1 && s[0] == '-' || i > 1 && s[i - 1] == '-' && is_number(s[i - 2]) == 0)
number *= -1;
i = k - 1;
stk_num[++top_num] = number;
}
// 处理符号部分
else
{
//将非符号部分排除
if((s[i] == '+' || s[i] == '-') && (i == 0 || s[i - 1] == '(' || (is_number(s[i - 1]) == 0 && s[i - 1] != ')')))
continue;
//讨论当 ')' 时的情况
if(s[i] == ')')
{
while(stk_fu[top_fu] != '(')
{
double a = stk_num[top_num--], b = stk_num[top_num--];
char c = stk_fu[top_fu--];
stk_num[++top_num] = fun(a, c, b);
}
top_fu--;
}
else
{
//普通情况
if(top_fu == 0)stk_fu[++top_fu] = s[i];
else
{
//如若s[i]大一级直接压栈 否则拿出来计算
if(check(stk_fu[top_fu], s[i]) == 1)stk_fu[++top_fu] = s[i];
else
{
//当符号栈为空或符号栈定优先级更大位置
while(top_fu != 0 && check(stk_fu[top_fu], s[i]) == 0)
{
double a = stk_num[top_num--], b = stk_num[top_num--];
char c = stk_fu[top_fu--];
stk_num[++top_num] = fun(a, c, b);
}
stk_fu[++top_fu] = s[i];
}
}
}
}
}
while(top_fu != 0)
{
double a = stk_num[top_num--], b = stk_num[top_num--];
char c = stk_fu[top_fu--];
stk_num[++top_num] = fun(a, c, b);
}
printf("%.1f\n", stk_num[top_num]);
}
return 0;
}

7-6 求前缀表达式的值

7-6

作者 DS课程组

单位 浙江大学

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。

输入格式:

输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。

输出格式:

输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR。

输入样例:

+ + 2 * 3 - 7 4 / 8 4

输出样例:

13.0

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-21 求前缀表达式的值 (25 分)c语言_前缀表达式求值算法c语言-CSDN博客)

#include<stdio.h>
#include<string.h>
typedef struct
{
int flag;//判断是数字或是运算符的标志
double num;//经过处理的运算数
char op;//运算符
}Stack;//打包成一个栈
int isnumber(char a)
{
if(a>=48&&a<=57)return 1;
return 0;
}
int main()
{
char c[31];//分块
Stack S[31],s1[31];
int top=0,i,top1=0;
while(scanf("%s",c)!=EOF)
{

//遇到数字了,进行处理
if(isnumber(c[0])||!isnumber(c[0])&&isnumber(c[1]))
{
int len=strlen(c),num=0;
double ps=0,pp=0.1;
//不带符号的数字
if(isnumber(c[0]))
{
for(i=0;i<len&&c[i]!='.';i++)//整数部分
{
num=num*10+c[i]-'0';
}//分成两部分好转化一点
if(c[i]=='.')//小数部分
{
for(;i<len;i++)
{
if(c[i]!='.')
{
ps+=(c[i]-'0')*pp;
pp*=0.1;
}
}
}
ps+=num;
}
//处理带正负符号的
else
{
for(i=1;i<len&&c[i]!='.';i++)
{
num=num*10+c[i]-'0';
}
if(c[i]=='.')
{
for(;i<len;i++)
{
if(c[i]!='.')
{
ps+=(c[i]-'0')*pp;
pp*=0.1;
}
}
}
ps+=num;
if(c[0]=='-')
ps=-ps;
}
//处理完后将数字入栈大S,记得标志为1
S[top].flag=1;
S[top].num=ps;
top++;
}
else
{
S[top].flag=0;//运算符标志为0,入栈大S
S[top].op=c[0];
top++;
}
}

while(top--)
{
//是数字 入栈数字栈s1
if(S[top].flag==1)s1[top1++].num=S[top].num;

else if(S[top].flag==0)
{
double a=s1[--top1].num,b=s1[--top1].num;
char c=S[top].op;
if(top1==-1)//当数字栈s1只剩下一个时退出就行了 不然最后一个测试点过不了
{
s1[0].num=a;
top1=1;
break;
}
switch(c)
{
case '+':
s1[top1++].num=a+b;
break;
case '-':
s1[top1++].num=a-b;
break;
case '*':
s1[top1++].num=a*b;
break;
case '/':
if(b==0)//分母为0
{
printf("ERROR");
return 0;
}
s1[top1++].num=a/b;
break;
}
}
}
printf("%.1f",s1[top1-1].num);
return 0;
}

7-7 简单计算器

7-7

作者 陈越

单位 浙江大学

cal.jpg

本题要求你为初学数据结构的小伙伴设计一款简单的利用堆栈执行的计算器。如上图所示,计算器由两个堆栈组成,一个堆栈 S1​ 存放数字,另一个堆栈 S2​ 存放运算符。计算器的最下方有一个等号键,每次按下这个键,计算器就执行以下操作:

  1. 从 S1​ 中弹出两个数字,顺序为 n1​ 和 n2​;
  2. 从 S2​ 中弹出一个运算符 op;
  3. 执行计算 n2​ op n1​;
  4. 将得到的结果压回 S1​。

直到两个堆栈都为空时,计算结束,最后的结果将显示在屏幕上。

输入格式:

输入首先在第一行给出正整数 N(1<N≤103),为 S1​ 中数字的个数。

第二行给出 N 个绝对值不超过 100 的整数;第三行给出 N−1 个运算符 —— 这里仅考虑 +、-、*、/ 这四种运算。一行中的数字和符号都以空格分隔。

输出格式:

将输入的数字和运算符按给定顺序分别压入堆栈 S1​ 和 S2​,将执行计算的最后结果输出。注意所有的计算都只取结果的整数部分。题目保证计算的中间和最后结果的绝对值都不超过 109。

如果执行除法时出现分母为零的非法操作,则在一行中输出:ERROR: X/0,其中 X 是当时的分子。然后结束程序。

输入样例 1:

5
40 5 8 3 2
/ * - +

输出样例 1:

2

输入样例 2:

5
2 5 8 4 4
* / - +

输出样例 2:

ERROR: 5/0

题目引用自团体程序设计天梯赛真题(2020年)。

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:(引用自L2-1 简单计算器 (25 分)详解c语言 模拟堆栈_本题要求你为初学数据结构的小伙伴设计一款简单的利用堆栈执行的计算器。如上图所-CSDN博客)

#include<stdio.h>
int digit(int a,int b,char c)//计算操作
{
if(c=='+')return a+b;
if(c=='-')return a-b;
if(c=='*')return a*b;
if(c=='/'&&b==0)
return -199;//如果出错就返回199;继续后续的ERROR打印
if(c=='/')return a/b;
else return 0;
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
char b[n-1];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
getchar();//要用getchar吸收空格和回车,一开始搞错了,找了很久的错误。
for(int i=0;i<n-1;i++)
{
scanf("%c",&b[i]);
getchar();
}
int sum=0;
int p = n-2;//p是字符数组的下标,因为有n-1个元素,所以末尾元素是n-2

for(int i=n-1;i>0;i--)
{
int tem = a[i-1];
a[i-1] = digit(a[i-1],a[i],b[p]);//计算后两位,然后结果给到倒数第二位
p--;
if(a[i-1]==-199)//哎,等于-199说明错误啦,所以输出然后直接返回。tem是为了存i-1的数值
//不然i-1就是-199啦,就会错的一塌糊涂。
{
printf("ERROR: %d/%d",tem,a[i]);
return 0;
}
}
printf("%d",a[0]);//全部计算完之后就只剩下a[0]啦
}

7-8 彩虹瓶

7-8

作者 陈越

单位 浙江大学

rb.JPG

彩虹瓶的制作过程(并不)是这样的:先把一大批空瓶铺放在装填场地上,然后按照一定的顺序将每种颜色的小球均匀撒到这批瓶子里。

假设彩虹瓶里要按顺序装 N 种颜色的小球(不妨将顺序就编号为 1 到 N)。现在工厂里有每种颜色的小球各一箱,工人需要一箱一箱地将小球从工厂里搬到装填场地。如果搬来的这箱小球正好是可以装填的颜色,就直接拆箱装填;如果不是,就把箱子先码放在一个临时货架上,码放的方法就是一箱一箱堆上去。当一种颜色装填完以后,先看看货架顶端的一箱是不是下一个要装填的颜色,如果是就取下来装填,否则去工厂里再搬一箱过来。

如果工厂里发货的顺序比较好,工人就可以顺利地完成装填。例如要按顺序装填 7 种颜色,工厂按照 7、6、1、3、2、5、4 这个顺序发货,则工人先拿到 7、6 两种不能装填的颜色,将其按照 7 在下、6 在上的顺序堆在货架上;拿到 1 时可以直接装填;拿到 3 时又得临时码放在 6 号颜色箱上;拿到 2 时可以直接装填;随后从货架顶取下 3 进行装填;然后拿到 5,临时码放到 6 上面;最后取了 4 号颜色直接装填;剩下的工作就是顺序从货架上取下 5、6、7 依次装填。

但如果工厂按照 3、1、5、4、2、6、7 这个顺序发货,工人就必须要愤怒地折腾货架了,因为装填完 2 号颜色以后,不把货架上的多个箱子搬下来就拿不到 3 号箱,就不可能顺利完成任务。

另外,货架的容量有限,如果要堆积的货物超过容量,工人也没办法顺利完成任务。例如工厂按照 7、6、5、4、3、2、1 这个顺序发货,如果货架够高,能码放 6 只箱子,那还是可以顺利完工的;但如果货架只能码放 5 只箱子,工人就又要愤怒了……

本题就请你判断一下,工厂的发货顺序能否让工人顺利完成任务。

输入格式:

输入首先在第一行给出 3 个正整数,分别是彩虹瓶的颜色数量 N(1<N≤103)、临时货架的容量 M(<N)、以及需要判断的发货顺序的数量 K。

随后 K 行,每行给出 N 个数字,是 1 到N 的一个排列,对应工厂的发货顺序。

一行中的数字都以空格分隔。

输出格式:

对每个发货顺序,如果工人可以愉快完工,就在一行中输出 YES;否则输出 NO。

输入样例:

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

输出样例:

YES
NO
NO**

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自PTA 彩虹瓶 (25分)_7-24 彩虹瓶 分数 25 作者 陈越 单位 浙江大学 rb.jpg 彩虹瓶的制作过程(并不)是-CSDN博客)

#include <iostream>
#include<cstdio>
#include<stack>
using namespace std;
int main() {
int n,m,k; //n:彩虹瓶的颜色数量 m:临时货架的容量 k:需要判断的发货顺序的数量
cin>>n >>m>>k;
for(int P=1; P<=k; P++) {
stack<int> hj;
hj.push(0);
int ban[n];
for(int j=0; j<n; j++) {
cin>>ban[j];
}
int color=1;
int i=0; //i是搬得次数
bool flag=true;
while(i<n) {
if(color!=hj.top()) {
if(color!=ban[i]) {
hj.push(ban[i]);
if(hj.size()-1>m) {
flag=false;
break;
}
} else {
color++;
}
i++;
} else {
hj.pop();
color++;
}
}
while(hj.size()!=1&&flag!=false) {
if(hj.top()!=color) {
flag=false;
break;
} else {
hj.pop();
color++;
}
}
if (flag)
cout << "YES" << endl;
else
cout << "NO" << endl;

}
return 0;
}

7-9 出栈序列的合法性

7-9

作者 陈越

单位 浙江大学

给定一个最大容量为 m 的堆栈,将 n 个数字按 1, 2, 3, …, n 的顺序入栈,允许按任何顺序出栈,则哪些数字序列是不可能得到的?例如给定 m=5、n=7,则我们有可能得到{ 1, 2, 3, 4, 5, 6, 7 },但不可能得到{ 3, 2, 1, 7, 5, 6, 4 }。

输入格式:

输入第一行给出 3 个不超过 1000 的正整数:m(堆栈最大容量)、n(入栈元素个数)、k(待检查的出栈序列个数)。最后 k 行,每行给出 n 个数字的出栈序列。所有同行数字以空格间隔。

输出格式:

对每一行出栈序列,如果其的确是有可能得到的合法序列,就在一行中输出YES,否则输出NO。

输入样例:

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

输出样例:

YES
NO
NO
YES
NO

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-13 出栈序列的合法性(25 分)_给定一个最大容量为 m 的堆栈,将 n 个数字按 1, 2, 3, …, n 的顺序入栈,允-CSDN博客)

#include<stdio.h>

int m,n,k;
int stack[1007]; //栈
int top=0; //栈顶下标
int index1=1,index2=1; //index1来表示1-n的数字 ,index2来表示数组b的下标
int b[1007]; //存放出栈序列

int main()
{
scanf("%d%d%d",&m,&n,&k);
while(k--)
{
int flag=1;
index1=1;index2=1;
top=0;
int i;
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
while(1)
{
//判断给出的出栈序列如果和1到n增长顺序相同,那就是入栈一个元素,然后立即出栈。
if(index1==b[index2])
{
index1++;
index2++;
}
//判断如果栈中有元素,然后栈顶元素也与此时的出栈序列元素相同,那么就继续出栈来判断
else if(top!=0&&stack[top-1]==b[index2])
{
top--;
index2++;
}
else
{
if(index1>n)break; //已经判断结束,就跳出循环
stack[top]=index1; //元素入栈
top++;
index1++;
if(top>=m) //
{
flag=0;
break;
}
}
}
if(flag==0||top!=0)printf("NO\n");
else printf("YES\n");
}

return 0;
}

二、2024.3.11——23软1数据结构实验一

数据结构-2

(1)函数题

数据结构-2.1

6-1 单链表 - 1. 结点类型

6-1

作者 李祥

单位 湖北经济学院

定义如下线性表(单链表)结点类型

typedef struct _LNODE_
{
LELEMENT data;
struct _LNODE_ *next;
} LNODE;

打开“线性表”项目,创建结点类型的头文件“LNode.h”,定义单链表结点类型。

LNode.h

#ifndef _LNode_h_
#define _LNode_h_
#include "LElement.h"

/* 你提交的代码将被嵌在这里 */

#endif

打开“main.c”,修改主函数对以上结点类型进行测试。

main.c

#include <stdio.h>
#include <stdlib.h>
#include "LNode.h"

int main()
{
LNODE *p;
LELEMENT x;
LElementInput(&x);
p = (LNODE*)malloc(sizeof(LNODE));
p->data = x;
p->next = NULL;
LElementOutput(&p->data);
putchar('\n');
if (p->next)
{
puts("Yes");
}
else
{
puts("No");
}
free(p);
p = NULL;
return 0;
}

输入样例

2.5

输出样例

2.5
No

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

typedef struct _LNODE_
{
LELEMENT data;
struct _LNODE_ *next;
} LNODE;

6-2 单链表 - 2. 创建线性表

6-2

作者 李祥

单位 湖北经济学院

定义如下线性表(单链表)类型。

typedef struct
{
    int length;
    LNODE *head;
} LLIST;

说明:线性表采用带附加头结点的单链表存储结构。length 为线性表的长度,head 为头指针。

请编写函数,创建线性表(单链表)。

函数原型

void LListCreate(LLIST *list);

说明:参数 list 是指示线性表(单链表)的指针。函数完成对线性表(单链表)的初始化:创建附加头结点,将线性表初始长度置为0。

打开“线性表”项目,创建线性表(单链表)类型的两个文件“LList.h”和“LList.c”。

在“LList.h”头文件中声明线性表(单链表)类型和相关的操作函数,在“LList.c”源程序文件中编写相关操作函数。修改“main.c”源程序文件中的主函数,对以上函数进行测试。

LList.h

#ifndef _LList_h_
#define _LList_h_

#include "LNode.h"

typedef struct
{
int length;
LNODE *head;
} LLIST;

void LListCreate(LLIST *list);

#endif

LList.c


#include <stdio.h>
#include <stdlib.h>
#include "LList.h"

/* 你提交的代码将被嵌在这里 */

main.c

#include <stdio.h>
#include "LList.h"

int main()
{
LLIST a;
LListCreate(&a);
printf("%d\n", a.length);
if (a.head != NULL && a.head->next == NULL)
{
puts("OK");
}
free(a.head);
return 0;
}

样例输入

注:无输入。

样例输出

0
OK

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void LListCreate(LLIST *list)
{
list->head = (LNODE*)malloc(sizeof(LNODE));
list->length = 0;
list->head->next = NULL;
}

6-3 单链表 - 9. 判断空表

6-3

作者 李祥

单位 湖北经济学院

请编写函数,判断线性表(单链表)是否为空表。

函数原型 int LListEmpty(const LLIST *list);

说明:参数 list 是指示线性表(单链表)的指针,若线性表为空表,则函数值为1(真),否则为0(假)。

修改主函数,对以上函数进行测试。

int main()
{
LLIST a;
LListCreate(&a);
LListInput(&a);
if (LListEmpty(&a))
{
puts("Yes");
}
else
{
puts("No");
}
LListDestroy(&a);
return 0;
}

输入样例1

( )

输出样例1

Yes

输入样例2

( 2.8, 3.9, 6.5 )

输出样例2

No

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int LListEmpty(const LLIST *list)
{
if(list->head->next)
return 0;
else
return 1;
}

6-4 单链表 - 7. 删除元素

6-4

作者 李祥

单位 湖北经济学院

请编写函数,在线性表(单链表)指定位序处删除(取走)数据元素。

函数原型

void LListRemove(LLIST *list, int index, LELEMENT *element);

说明:参数 list 是指示线性表(单链表)的指针,index 是位序,element 是指示数据元素的指针。函数在 list 所指示的线性表位序 index 处删除数据元素,将其保存到 element 所指示的数据元素中。

要求:假设线性表长度为 n(n≥0),位序为 i,若 1≤i≤n,则在 i 处删除数据元素;否则报告错误:“Incorrect index!”,不删除数据元素。

修改主函数,对以上函数进行测试。

int main()
{
int n, i;
LELEMENT x;
LLIST a;
LListCreate(&a);
scanf("%d", &n);
while (n--)
{
scanf("%d", &i);
LElementInput(&x);
LListInsert(&a, i, &x);
}
LListOutput(&a);
putchar('\n');
scanf("%d", &n);
while (n--)
{
scanf("%d", &i);
LListRemove(&a, i, &x);
LListOutput(&a);
putchar(' ');
LElementOutput(&x);
putchar('\n');
}
LListDestroy(&a);
return 0;
}

输入样例

5 1 8.5 2 2.7 3 6.3 4 4.9 5 1.6 4 1 3 5 0

输出样例

( 8.5, 2.7, 6.3, 4.9, 1.6 )
( 2.7, 6.3, 4.9, 1.6 ) 8.5
( 2.7, 6.3, 1.6 ) 4.9
Incorrect index!
( 2.7, 6.3, 1.6 ) 4.9
Incorrect index!
( 2.7, 6.3, 1.6 ) 4.9

运行效果

5
1 8.5
2 2.7
3 6.3
4 4.9
5 1.6
( 8.5, 2.7, 6.3, 4.9, 1.6 )
4
1
( 2.7, 6.3, 4.9, 1.6 ) 8.5
3
( 2.7, 6.3, 1.6 ) 4.9
5
Incorrect index!
( 2.7, 6.3, 1.6 ) 4.9
0
Incorrect index!
( 2.7, 6.3, 1.6 ) 4.9

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void LListRemove(LLIST *list, int index, LELEMENT *element)
{

if(index<1||index>list->length)
printf("Incorrect index!\n");
else
{
LNODE *p=list->head;
for(int i=0;i<index-1;i++)
p=p->next;

LNODE *t=p->next;
*element=t->data;
p->next=t->next;
list->length--;
}
}

6-5 单链表 - 5. 插入元素

6-5

作者 李祥

单位 湖北经济学院

请编写函数,在线性表(单链表)指定位序处插入数据元素。

函数原型

void LListInsert(LLIST *list, int index, const LELEMENT *element);

说明:参数 list 是指示线性表(单链表)的指针,index 是位序,element 是指示数据元素的指针。函数在 list 所指示的线性表位序 index 处插入 element 所指示的数据元素。

要求:假设线性表长度为 n(n≥0),插入位序为 i,若 1≤i≤n+1,则在 i 处插入数据元素;否则报告错误:“Incorrect index!”,不插入数据元素。

修改主函数,对以上函数进行测试。

int main()
{
int n, i;
LELEMENT x;
LNODE *p;
LLIST a;
LListCreate(&a);
scanf("%d", &n);
while (n--)
{
scanf("%d", &i);
LElementInput(&x);
LListInsert(&a, i, &x);
}
p = a.head->next;
while (p)
{
if (p != a.head->next)
{
putchar(' ');
}
LElementOutput(&p->data);
p = p->next;
}
putchar('\n');
LListDestroy(&a);
return 0;
}

输入样例

24
1 3.8
2 6.5
5 4.7
0 9.2
3 7.1
4 0.9
1 2.8
7 1.8
4 8.3
9 7.6
5 3.1
2 9.6
3 7.9
1 8.7
8 0.4
3 6.2
9 1.7
6 4.5
7 5.2
7 1.6
2 9.5
9 2.4
8 4.7
7 5.6

输出样例

Incorrect index!
Incorrect index!
Incorrect index!
Incorrect index!
8.7 9.5 2.8 6.2 9.6 7.9 5.6 4.5 4.7 1.6 2.4 5.2 3.8 6.5 8.3 1.7 0.4 3.1 7.1 0.9

运行效果

24
1 3.8
2 6.5
5 4.7
Incorrect index!
0 9.2
Incorrect index!
3 7.1
4 0.9
1 2.8
7 1.8
Incorrect index!
4 8.3
9 7.6
Incorrect index!
5 3.1
2 9.6
3 7.9
1 8.7
8 0.4
3 6.2
9 1.7
6 4.5
7 5.2
7 1.6
2 9.5
9 2.4
8 4.7
7 5.6
8.7 9.5 2.8 6.2 9.6 7.9 5.6 4.5 4.7 1.6 2.4 5.2 3.8 6.5 8.3 1.7 0.4 3.1 7.1 0.9

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void LListInsert(LLIST *list, int index, const LELEMENT *element)
{
LNODE *m=list->head;
if(index<1||index>list->length+1)
{
printf("Incorrect index!\n");
return;
}
for(int i=0;i<index-1;i++)
m=m->next;
LNODE *n;
n=(LNODE*)malloc(sizeof(LNODE));
n->data=*element;
n->next=m->next;
m->next=n;
list->length++;
}

6-6 单链表去重*

6-6

作者 李祥

单位 湖北经济学院

已知单链表的结点结构定义如下:

        typedef struct _NODE_
{
int data;
struct _NODE_ *next;
} NODE;

说明:data 为数据域。next 为指针域,指示后继结点。

请编写函数,删除带附加头结点的单链表中重复的数据结点。

函数原型
void Unique(NODE *head);

说明:参数 head 为单链表的头指针,函数将删除单链表中重复的数据结点。

裁判程序

int main()
{
NODE *h;
Create(&h);
Input(h);
Unique(a);
Output(a);
putchar('\n');
Destroy(&a);
return 0;
}

说明:Create 函数用于创建链表,Destroy 函数用于销毁链表。Input 函数用于输入链表:首先输入结点数,然后输入这些数据元素。Output 函数用于输出单链表,数据元素之间以空格间隔。

输入样例

16
28 47 52 28 36 47 52 47 28 28 95 47 36 28 47 95

输出样例

28 47 52 36 95

要求:时间复杂度为 O(n²),空间复杂度为 O(1)。

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void Unique(NODE *head)
{
NODE *m=head->next;
while(m!=NULL)
{
NODE *p=m;
while(p->next!=NULL)
{
if(p->next->data==m->data)
{
NODE *t=p->next;
p->next=t->next;
free(t);
}
else
{
p=p->next;
}
}
m=m->next;
}

}

(2)编程题

数据结构-2.2

7-1最大子列和问题

7-1

作者 DS课程组

单位 浙江大学

给定K个整数组成的序列{ N1​, N2​, …, NK​ },“连续子列”被定义为{ Ni​, Ni+1​, …, Nj​ },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。

本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:

  • 数据1:与样例等价,测试基本正确性;

  • 数据2:102个随机整数;

  • 数据3:103个随机整数;

  • 数据4:104个随机整数;

  • 数据5:105个随机整数;

输入格式:

输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。

输出格式:

在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。

输入样例:

6
-2 11 -4 13 -5 -2

输出样例:

20

代码长度限制:16 KB

时间限制:10000 ms

内存限制:64 MB

答案:(引用自7-1 最大子列和问题-CSDN博客)

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int a,i,s[1000000],sum=0,max=0;
scanf("%d",&a);
for(i=0;i<a;i++)
scanf("%d",&s[i]);
for(i=0;i<a;i++)
{
sum+=s[i];
if(sum>max)
max=sum;
if(sum<0)
sum=0;
}
printf("%d",max);
return 0;
}

7-2 一元多项式的乘法与加法运算

7-2

作者 DS课程组

单位 浙江大学

设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:

输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。

输入样例:

4 3 4 -5 2  6 1  -2 0
3 5 20 -7 4 3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

代码长度限制:16 KB

时间限制:200 ms

内存限制:64 MB

答案:(引用自7-2 一元多项式的乘法与加法运算-CSDN博客)

#include<bits/stdc++.h>
using namespace std;
struct X
{
int xs;//系数
int zs;//指数
}a[100], b[100], x[1000], j[200];//x[]数组是乘法结果j[]数组是加法结果
bool cmp(X q, X w)
{
return q.zs > w.zs;
}//排序指数降序
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i].xs >> a[i].zs;
}
int m;
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> b[i].xs >> b[i].zs;
}
int i = 0;
int r = n, l = m;//将项数赋值给r,l
int t = 0;
int p;
for (int j = 0; j < r; j++)
{
for (int k = 0; k < l; k++)
{
p = t;
while (--p >= 0)
{
if (x[p].zs == a[j].zs + b[k].zs)
{
x[p].xs += a[j].xs * b[k].xs;
break;//向前寻找指数一样的项进行合并
}
}
if (p < 0)//无法合并直接进入数组
{
x[t].xs = a[j].xs * b[k].xs;
x[t].zs = a[j].zs + b[k].zs;
t++;
}
}
}
sort(x, x + t, cmp);//指数降序排列
int aa = 0;
int jj = 0, jjj = 0;
while (x[jj].xs != 0)
{
cout << x[jj].xs << " " << x[jj].zs; aa++; jj++; jjj++;
if (jjj != 0)
{
break;
}
}//while循环为了输出第一个前面无空格非零项,因为格式要求最后无多余空格,所以将每项间的空格放置下一项的开头
for (int j = jj; j < t; j++)
{
if (x[j].xs != 0)
{ cout << " " << x[j].xs << " " << x[j].zs; aa++; }
}
/*if (x[t - 1].xs != 0) { cout << x[t - 1].xs << " " << x[t - 1].zs; aa++; }*/
if (aa == 0)
{
cout << "0" << " " << "0";
}//判断是否全部都消掉
aa = 0;
cout << "\n";
while (n > 0 || m > 0)
{
if (n <= 0)
{
//a[]数组全加减完了,b[]直接全部进入数组j[]
j[i].xs = b[l - m].xs, j[i].zs = b[l - m].zs, m -= 1;
i++;
}
if (m <= 0)
{
//b[]数组全加减完了
j[i].xs = a[r - n].xs, j[i].zs = a[r - n].zs, n -= 1;
i++;
}
if (n > 0 && m > 0)
{
if (a[r - n].zs == b[l - m].zs)
{
j[i].zs = a[r - n].zs, j[i].xs = a[r - n].xs + b[l - m].xs;
i++, m--, n--;

}
if (a[r - n].zs > b[l - m].zs)
{
j[i].zs = a[r - n].zs, j[i].xs = a[r - n].xs;
i++, n--;

}
if (a[r - n].zs < b[l - m].zs)
{
j[i].zs = b[l - m].zs, j[i].xs = b[l - m].xs;
i++, m--;

}
}
}
int kk = 0, kkk = 0;
while (j[kk].xs != 0)
{
cout << j[kk].xs << " " << j[kk].zs; aa++; kkk++; kk++;
if (kkk != 0)
{ break; }
}
for (int k = kk; k < i; k++)
{
if (j[k].xs != 0)
{ cout << " " << j[k].xs << " " << j[k].zs; aa++; }
}
if (aa == 0)
{
cout << "0" << " " << "0";
}
}

7-3 求链式线性表的倒数第K项

7-3

作者 DS课程组

单位 浙江大学

给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。

输入格式:

输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。

输出格式:

输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL。

输入样例:

4 1 2 3 4 5 6 7 8 9 0 -1

输出样例:

7

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct LNode * List;
struct LNode
{
int data;
List next;
};
int main()
{
int cnt = 0;
int data;
List head = (List)malloc(sizeof(struct LNode));
head->next = NULL;
List temp;
List p = head;
int k,i;
scanf("%d",&k);
while(scanf("%d",&data)!= EOF && data >= 0)
{
temp = (List)malloc(sizeof(struct LNode));
temp->data = data;
temp->next = NULL;
p->next = temp;
p = temp;
cnt++;
}
if(cnt < 1 || k > cnt)
{
printf("NULL");
}
else
{
p = head;
for(i = 1; i <= cnt - k + 1; i++)
{
p = p->next;
}
printf("%d",p->data);
}
}

一、2024.3.2——数据结构第1次作业

数据结构-1

(1)函数题

数据结构-1.1

6-1 递增的整数序列链表的插入

6-1

作者 DS课程组

单位 浙江大学

本题要求实现一个函数,在递增的整数序列链表(带头结点)中插入一个新整数,并保持该序列的有序性。

函数接口定义:

List Insert( List L, ElementType X );

其中List结构定义如下:

typedef struct Node *PtrToNode;
struct Node {
ElementType Data; /* 存储结点数据 */
PtrToNode Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L是给定的带头结点的单链表,其结点存储的数据是递增有序的;函数Insert要将X插入L,并保持该序列的有序性,返回插入后的链表头指针。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;

List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表 */

List Insert( List L, ElementType X );

int main()
{
List L;
ElementType X;
L = Read();
scanf("%d", &X);
L = Insert(L, X);
Print(L);
return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

5
1 2 4 5 6
3

输出样例:

1 2 3 4 5 6

代码长度限制: 16 KB

时间限制: 400 ms

内存限制: 64 MB

答案:( 引用自递增的整数序列链表的插入—PTA_递增的整数序列链表的插入算法pta-CSDN博客)

List Insert( List L, ElementType X )
{
struct Node *head=L,*p;
p=(struct Node*)malloc(sizeof(struct Node));
p->Next=NULL;
p->Data=X;
while(L->Next!=NULL&&L->Next->Data<X)
{
L=L->Next;
}
p->Next=L->Next;
L->Next=p;
return head;
}

6-2 两个有序链表序列的合并

6-2

作者 DS课程组

单位 浙江大学

本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个非递减的整数序列。

函数接口定义:

List Merge( List L1, List L2 );

其中List结构定义如下:

typedef struct Node *PtrToNode;
struct Node {
ElementType Data; /* 存储结点数据 */
PtrToNode Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L1和L2是给定的带头结点的单链表,其结点存储的数据是递增有序的;函数Merge要将L1和L2合并为一个非递减的整数序列。应直接使用原序列中的结点,返回归并后的带头结点的链表头指针。

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表;空链表将输出NULL */
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
/* 你的代码将被嵌在这里 */

输入样例:

3
1 3 5
5
2 4 6 8 10

输出样例:

1 2 3 4 5 6 8 10 
NULL
NULL

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自6-2 两个有序链表序列的合并 (20 分) 本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个非递减的整数序列。_本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个非递减的整数序列-CSDN博客)

List Merge(List L1, List L2)
{
struct Node* Head = (struct Node*)malloc(sizeof(struct Node));
struct Node* p= Head;
struct Node* p1 = L1->Next;
struct Node* p2 = L2->Next;
while (p1 && p2)
{
if (p1->Data <= p2->Data)
{
p->Next = p1;
p = p->Next;
p1 = p1->Next;
}
else if (p1->Data > p2->Data)
{
p->Next = p2;
p = p->Next;
p2 = p2->Next;
}
}
if (p1)
p->Next = p1;
if (p2)
p->Next = p2;
L1->Next = NULL;
L2 ->Next= NULL;
return Head;
}


(2)编程题

数据结构-1.2

7-1最大子列和问题

7-1

作者 DS课程组

单位 浙江大学

给定K个整数组成的序列{ N1​, N2​, …, NK​ },“连续子列”被定义为{ Ni​, Ni+1​, …, Nj​ },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。

本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:

  • 数据1:与样例等价,测试基本正确性;

  • 数据2:102个随机整数;

  • 数据3:103个随机整数;

  • 数据4:104个随机整数;

  • 数据5:105个随机整数;
    输入格式:

输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。

输出格式:

在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。

输入样例:

6
-2 11 -4 13 -5 -2

输出样例:

20

代码长度限制:16 KB

时间限制:10000 ms

内存限制:64 MB

答案:(引用自7-1 最大子列和问题-CSDN博客)

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int a,i,s[1000000],sum=0,max=0;
scanf("%d",&a);
for(i=0;i<a;i++)
scanf("%d",&s[i]);
for(i=0;i<a;i++)
{
sum+=s[i];
if(sum>max)
max=sum;
if(sum<0)
sum=0;
}
printf("%d",max);
return 0;
}

7-2 数组循环左移

7-2

作者 DS课程组

单位 浙江大学

本题要求实现一个对数组进行循环左移的简单函数:一个数组a中存有n(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向左移m(≥0)个位置,即将a中的数据由(a0​a1​⋯an−1​)变换为(am​⋯an−1​a0​a1​⋯am−1​)(最前面的m个数循环移至最后面的m个位置)。如果还需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

输入格式:

输入第1行给出正整数n(≤100)和整数m(≥0);第2行给出n个整数,其间以空格分隔。

输出格式:

在一行中输出循环左移m位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

8 3
1 2 3 4 5 6 7 8

输出样例:

4 5 6 7 8 1 2 3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自7-2 数组循环左移-CSDN博客)

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
int n,m,i,s[100];
scanf("%d %d",&n,&m);
for(i=0;i<n;i++)
scanf("%d",&s[i]);
m=m%n;
for(i=m;i<n;i++)
{
printf("%d",s[i]);
if(i!=n-1)
printf(" ");
}
for(i=0;i<m;i++)
printf(" %d",s[i]);
return 0;
}

C++

十九、2024.6.07—2024春面向对象程序设计作业10

C++-19

(1)单选题

C++-19.1

2-1(A)

vector容器中,( )可以返回vector当前元素的数量。

A.size()

B.capacity()

C.max_size()

D.empty()

2-2(D)

下列关于STL的描述中,错误的是。

A.STL的内容从广义上讲分为容器、迭代器、算法三个主要部分

B.STL的一个基本理念就是将数据和操作分离

C.STL中的所有组件都由模板构成,其元素可以是任意类型

D.STL的容器、迭代器、算法是三个完全独立的部分,彼此也无任何联系

2-3(D)

关于STL之stack和queue的以下说法中,错误的是( )。

A.stack的push方法(成员函数)用于将元素入栈

B.queue的push方法(成员函数)用于将元素入队

C.queue的front方法(成员函数)用于取得队头元素

D.stack的top方法(成员函数)用于取得栈顶元素的下标

2-4(C)

对磁盘文件进行操作时,以__模式打开的文件,可实现创建一个可以写入的、新的空文件;如果该文件已经存在,则先删除以前的内容,再写入新数据。

A.ios::in

B.ios::app

C.ios::out

D.ios::binary

2-5(A)

使用“myFile.open(“Sales.dat”,ios::app);”语句打开文件Sales.date后,则()。

A.该文件只能用于输出

B.该文件只能用于输入

C.该文件既可以用于输出,也可以用于输入

D.若该文件存在,则清除该文件的内容

2-6(A)

句“void Set(A &a);”是类A中的一个成员函数的声明,其中A &a的含义是( )。

A.类A的对象引用a作该函数的参数

B.类A的对象a的地址值做函数的参数

C.表达式变量A与变量a按位与作函数参数

D.指向类A对象指针a作函数参数

2-7(A)

关于this指针的以下说法,正确的是()。

A.当创建一个对象后,this指针就指向该对象

B.this指针必须显式说明

C.this指针指向成员函数

D.this指针的值不会随着对象的不同而改变

2-8(C)

当变量x的输入值是9时,下面程序的运行结果是:

#include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
cin>>x;
try
{
cout<<"begin"<<endl;
if(x>100)
{
cout<<"1"<<endl;
throw string("too big.");
}
else
{
cout<<"x="<<x<<endl;
}
cout<<"2"<<endl;
}
catch(string e)
{
cout<<"3:"<<e<<endl;
}
cout<<"end"<<endl;
return 0;
}

A.

begin
1
2
end

B.

begin
1
3: too big.
2
end

C.

begin
x=9
2
end

D.

begin
1
3: too big.
end

2-9(A)

下列关于运算符重载的描述中,错误的是()。

A.运算符重载后,原来运算符操作不可再用

B.运算符重载不改变优先级

C.运算符重载函数的参数个数与重载方式有关

D.运算符重载不改变结合性

2-10(D)

下列运算符中,不能被重载的是( )

A. +

B. ++

C. =

D. ?:

(2)程序填空题

C++-19.2

5-1 多继承练习

C++-5-1

作者 王荣海

单位 泉州师范学院

以下是多继承相关的程序,请完成程序填空。

输入样例:
100 200 300
输出样例:
Constructor X1.
Constructor X2.
Constructor A.
100
200
300
#include <iostream>
using namespace std;
class X1{
public:
        X1(int i)
{
x1=i;
cout<<"Constructor X1. "<<endl;
}
void print ()
{
cout<<x1<<endl;
}
private:int x1;
};
class X2{
public:
        X2(int i)
{
x2=i;
cout<<"Constructor X2. "<<endl;
}
void print ()
{
cout<<x2<<endl;
}
private:int x2;
};
class A:public X1,public X2{
public:
        A(int i,int j,int l);
void print();
private:
int a;
};
A::A(int i,int j,int l):X1(i),X2(j)
{
a=l;
cout<<"Constructor A. "<<endl;
}
void A::print()
{
X1::print();
X2::print();
cout<<a<<endl;
}
int main() {
    int k,n,m;
cin>>m>>n>>k;
    A aa(m,n,k);
aa.print();
return 0;
}

答案:

第一空:

X1(int i)

第二空:

X2(int i)

第三空:

A(int i,int j,int l);

第四空:

int k,n,m;

5-2 访问声明的应用

C++-5-2

作者 王荣海

单位 泉州师范学院

以下是关于访问声明应用的程序,请完成程序填空。

输入样例:
100
输出样例:
a=100
#include<iostream>
using namespace std;
class A{
int x;
public:
A(int x1){x=x1;}
void show(){cout<<"x="<<x;}
void show(int a){cout<<"a="<<a;}
};
class B: private A{
int y;
public:
B(int x1,int y1):A(x1){y=y1;}
void show(int a){A::show(a);}
};
int main() {
int a;
cin>>a;
B b(10,20);
b.show(a);
return 0;
}

答案:

第一空:

int a

第二空:

void show(int a){A::show(a);}

第三空:

show(a)

5-3 转换构造函数的应用

C++-5-3

作者 王荣海

单位 泉州师范学院

以下是关于转换构造函数应用的程序,请完成程序填空。

输出结果:
8.8+3.3i
//转换构造函数的应用 
#include<iostream>
using namespace std;
class Complex{
public:
Complex(){ }
Complex(double r,double i)
{ real=r; imag=i;}
Complex(double r){real=r;}
friend Complex operator+(Complex &co1,Complex &co2);
void print();
private:
double real;
double imag;
};
Complex operator+(Complex &co1,Complex &co2) {
Complex temp;
temp.real=co1.real+co2.real;
temp.imag=co1.imag+co2.imag;
return temp;
}
void Complex::print( ) {
cout<<real;
if (imag>0) cout<<"+";
if (imag!=0) cout<<imag<<"i\n";
}
int main( ) {
Complex com1(2.2,3.3),total,com2;
com2=Complex(6.6);
total=com1+com2;
total.print();
return 0;
}

答案:

第一空:

real=r;

第二空:

temp.real=co1.real+co2.real;

第三空:

"+"

第四空:

total=com1+com2;

5-4 点类的定义和使用

C++-5-4

作者 GONG

单位 哈尔滨华德学院

已知平面上的一点由其横纵坐标来标识。本题要求按照已给代码和注释完成一个基本的“点”类的定义(坐标均取整型数值)。并通过主函数中的点类对象完成一些简单操作,分析程序运行结果,将答案写在对应的空格中。

#include <iostream>
using namespace std;
class Point
{
private://访问权限设置,私有权限
int x;//横坐标
int y;//纵坐标
public://访问权限设置,公有权限

//以下为构造函数,用参数a,b分别为横纵坐标进行初始化
Point(int a,int b)
{
x=a;
y=b;
}

//以下为拷贝构造函数,借用对象a_point完成初始化
Point(Point &a_point)
{
x=a_point.x;
y=a_point.y;
}

~Point()//以下为析构函数

{
cout<<"Deconstructed Point";
print();
}

//以下为输出点的信息的函数,要求在一行中输出点的坐标信息,形如:(横坐标,纵坐标)
void print()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};


int main()
{
Point b_point(0,0);
b_point.print();
int a,b;
cin>>a>>b;//从标准输入流中提取数值给a,b
Point c_point(a,b);
c_point.print();
return 0;//主函数的返回语句
}
/*设输入为10 10,则本程序的运行结果为:
(0,0)
(10,10)
Deconstructed Point(10,10)
Deconstructed Point(0,0)
*/

答案:

第一空:

iostream

第二空:

private:

第三空:

public:

第四空:

Point

第五空:

x=a

第六空:

y=b

第七空:

Point &

第八空:

~Point()

第九空:

"("<<x<<","<<y<<")"

第十空:

cin>>a>>b;

第十一空:

return 0;

第十二空:

(0,0)

第十三空:

(10,10)

第十四空:

Deconstructed Point(10,10)

第十五空:

Deconstructed Point(0,0)

5-5 包含子对象的派生类构造函数

C++-5-5

作者 范鹏程

单位 内蒙古师范大学

根据所定义的基类,定义派生类,请填空完成程序的功能

#include <iostream>
#include <string>
using namespace std;
class Student //声明基类
{public: //公用部分
Student(int n,string nam) //基类构造函数
{num=n;
name=nam;
}
void display() //输出基类数据成员
{cout<<"num:"<<num<<endl<<"name:"<<name<<endl;}
protected: //保护部分
int num;
string name;
};

class Student1: public Student //用public继承方式声明派生类student
{public:
Student1(int n1,string nam1,int mnum,string mstring,int a,string ad):Student(n1,nam1),monitor(mnum,mstring) //派生类构造函数
{age=a; //在此处只对派生类新增的数据成员初始化
addr=ad;
}
void show( )
{cout<<"This student is:"<<endl;
display(); //输出num和name
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl<<endl;
}

void show_monitor() //输出子对象的数据成员
{cout<<endl<<"Class monitor is:"<<endl;
monitor.display(); //调用基类成员函数
}
private: //派生类的私有数据
Student monitor; //定义子对象(班长)
int age;
string addr;
};

int main( )
{Student1 stud1(10010,"Wang-li",10001,"Li-sun",19,"115 Beijing Road,Shanghai");
stud1.show( ); //输出第一个学生的数据
stud1.show_monitor(); //输出子对象的数据
return 0;
}

程序输出如下

This student is:
num:10010
name:Wang-li
age: 19
address: 115 Beijing Road,Shanghai


Class monitor is:
num:10001
name:Li-sun

答案:

第一空:

Student1(int n1,string nam1,int mnum,string mstring,int a,string ad):Student(n1,nam1),monitor(mnum,mstring)

5-6 年龄小的小朋友先吃糖 - 《C++编程基础及应用》- 习题19-4

C++-5-6

作者 海洋饼干叔叔

单位 重庆大学

幼稚园阿姨发糖,不考虑排队次序,总是年龄小的小朋友先领到糖。请查询资料,使用优先队列(priority_queue)容器来模拟不同年龄的小朋友先后到达(入队)并按年龄从小到大领糖的过程。

提示:

  1. 应定义Child类型,该类型至少包括小朋友姓名,小朋友年龄两个数据成员;
  2. 定义合适的函数依据年龄比较两个小朋友对象的大小。
 #include <iostream>
#include <queue>
using namespace std;

class Child {
public:
string sName;
int iAge;

bool operator>(Child c) const{
return iAge>c.iAge;;
}

Child(string name, int age){
sName = name;
        iAge=age;
}
};

int main()
{
priority_queue<Child,vector<Child>,greater<Child>> q;
q.push(Child("Jack",7));
q.push(Child("Tom",5));
q.push(Child("Tiffany",9));
q.push(Child("Alex",10));
q.push(Child("Dick",4));
q.push(Child("Jimmy",8));

while (!q.empty()){
auto x = q.top();
cout << x.sName << " at age " << x.iAge << " get candy." << endl;
        q.pop();
}
return 0;
}

期望的执行结果:

Dick at age 4 get candy.
Tom at age 5 get candy.
Jack at age 7 get candy.
Jimmy at age 8 get candy.
Tiffany at age 9 get candy.
Alex at age 10 get candy.

答案:

第一空:

Child c

第二空:

iAge>c.iAge;

第三空:

iAge=age;

第四空:

!q.empty()

第五空:

q.pop();

5-7 知识点2:static修饰的成员变量与成员函数

C++-5-7

作者 郑远

单位 中国民用航空飞行学院

静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员静态成员分为:

  • 静态成员变量 所有对象共享同一份数据 在编译阶段分配内存 静态成员变量定义语法 static 变量类型 变量名 类内声明,类外初始化,初始化语法为:变量类型 类名::变量名=初始化数(整体位于类定义的外面) * 可以通过对象或类进行调用:对象.静态成员变量名或类名::静态成员变量名

  • 静态成员函数 所有对象共享同一个函数 静态成员函数只能访问静态成员变量 静态成员函数定义语法:static 函数名(){} 可以通过对象或类进行调用:对象.静态函数名()或类名::静态函数名()

#include<iostream>
using namespace std;
class Person
{

public:
static int m_A; //静态成员变量
static void func() //静态成员函数func,没有输入
{
cout << "func调用" << endl;
m_A = 100;
//m_B = 100; //静态成员函数不可以访问非静态成员变量,这句话会报错
}
private:
static void func2()//静态成员函数也是有访问权限的
{
cout << "func2调用" << endl;
}
static int m_B; //静态成员变量也是有访问权限的
};
//静态成员变量初始化,私有对象可以在外面初始化但访问不了
int Person::m_A = 10;//初始化m_A
int Person::m_B = 10;
int main() {
//静态成员变量两种访问方式
//1、通过对象
Person p1;
p1.m_A = 100;//通过对象调用m_A
cout << "p1.m_A = " << p1.m_A << endl;

Person p2;
p2.m_A = 200;
cout << "p1.m_A = " << p1.m_A << endl; //共享同一份数据
cout << "p2.m_A = " << p2.m_A << endl;

//2、通过类名
cout << "m_A = " << Person::m_A << endl;//通过类名调用m_A
//cout << "m_B = " << Person::m_B << endl; //私有权限访问不到


//静态成员函数两种访问方式
//1、通过对象
Person p3;
p3.func(); //通过对象调用成员函数
//2、通过类名
Person::func(); //通过类调用成员函数
//Person::func2(); //私有权限访问不到


return 0;
}

答案:

第一空:

static int

第二空:

static void func()

第三空:

int Person::m_A

第四空:

p1.m_A

第五空:

Person::m_A

第六空:

p3.func();

第七空:

Person::func();

5-8 知识点3:递增运算符重载

C++-5-8

作者 郑远

单位 中国民用航空飞行学院

#include<iostream>

using namespace std;
class MyInteger {

friend ostream& operator<<(ostream& out, MyInteger myint);

public:
MyInteger() {
m_Num = 0;
}
//前置++
MyInteger operator++() {
//先++
m_Num++;
//再返回
return *this;
}

//后置++
MyInteger operator++(int)
{
//先返回
MyInteger t(*this); //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
m_Num++;
return t;
}

private:
int m_Num;
};


ostream& operator<<(ostream& out, MyInteger myint) {
out << myint.m_Num;
return out;
}


//前置++ 先++ 再返回
void test01() {
MyInteger myInt;
cout << ++myInt << endl;
cout << myInt << endl;
}

//后置++ 先返回 再++
void test02() {

MyInteger myInt;
cout << myInt++ << endl;
cout << myInt << endl;
}

int main() {

test01();
//test02();

system("pause");

return 0;
}

答案:

第一空:

MyInteger operator++

第二空:

m_Num++;

第三空:

return *this;

第四空:

MyInteger operator++(int)

第五空:

MyInteger t(*this);

第六空:

return t;

(3)函数题

C++-18.3

6-1 筛法求质数

6-1

作者 李廷元

单位 中国民用航空飞行学院

本题要求使用筛法求出1~N以内的质数。

函数接口定义:

vector<int> sieve(int n); //函数声明, 求n以内的质数

求n以内的质数。其中 n是传入的参数。n 的值不超过10 000 000的范围; 求出的质数存入容器vector并返回。

裁判测试程序样例:

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

vector<int> sieve(int n); //函数声明,求n以内的质数

int main(int argc, char const *argv[])
{
int n;
cin >> n;

vector<int> ans = sieve(n);

cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++) {
cout << ans[i];
if (i < ans.size() - 1)cout << " ";
}
cout << endl;

return 0;
}

/* 请在这里填写答案 */

输入样例:

输入在一行中给出一个正整数N,其值不超过10 000 000。

10

输出样例:

输出首先在一行中输出指定范围内的质数个数,然后在另一行输出指定范围内的所有质数,以空格分隔,但是最后一个质数后面没有多余空格。

4
2 3 5 7

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:(引用自6-181 筛法求质数 (15分)_6-1 筛法求质数-CSDN博客)

#include<string.h>
bool a[10000002];
vector<int> sieve(int n) {
vector<int> temp;
int cont = 0;
memset(a, true, sizeof(a));
for (int i = 2; i <= n; ++i) {
if (a[i]) {
temp.push_back(i);//加入数组
}
cont = temp.size();//在这里得到,数组的元素个数,可以避免for循环内反复调用函数,节省时间
for (int j = 0; j < cont&&temp[j]*i<=n; ++j) {
a[temp[j] * i] = false;
if (i % temp[j] == 0) {//避免重复标记//当前数i 是当前素数的倍数,则后面的素数乘以当前数肯定是当前数的倍数,会造成重复标记,所以遇到整除要结束当前循环的标记,进入下一轮
break;
}
}
}
return temp;
}

6-2 你好,下标运算符[]的重载

6-2

作者 向训文

单位 惠州学院

完善Tuple类的定义,使得程序可以正确运行:

裁判测试程序样例:

#include <iostream>
using namespace std;

// 请将答案填写在这里

int main() {
int v1, v2;
cin >> v1 >> v2;
Tuple v(v1, v2);
v[0] += 3;
v[1] *= 3;
cout << v[0] << endl;
cout << v[1] << endl;
return 0;
}

输入样例:

在这里给出一组输入。例如:

1 1

输出样例:

在这里给出相应的输出。例如:

4
3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Tuple
{
public:
int v[2];
Tuple(int m1,int m2)
{v[0]=m1;v[1]=m2;}
int &operator[](int n)
{
return v[n];
}
};

6-3 你好,虚函数

6-3

作者 向训文

单位 惠州学院

请完成Pet类的定义,使得程序正确运行:

裁判测试程序样例:

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

// 请将答案填写在这里

class Dog: public Pet {
public:
void speak(const string &s) {
cout << "dog says: " << s << endl;
}
};

int main() {
string word1, word2;
cin >> word1 >> word2;
Pet pet;
Dog dog;
Pet *p;
p = &pet;
p->speak(word1);
p = &dog;
p->speak(word2);
return 0;
}

输入样例:

第一行:pet说的话

第二行:dog说的话

hi
wang

输出样例:

在这里给出相应的输出。例如:

pet says: hi
dog says: wang

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Pet
{
public:
void virtual speak(const string &s)
{
cout << "pet says: " << s << endl;
}
};

6-4 你好,友员函数

6-4

作者 向训文

单位 惠州学院

完善类Point和函数calcDistance(计算两个点的距离,它是Point类的友员函数)的定义,使程序正确运行:

裁判测试程序样例:

#include <iostream>
#include <cmath> // 可以使用sqrt函数
using namespace std;

// 请将答案填写在这里

int main() {
double x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2; // 输入两个点的x, y坐标
Point p1(x1, y1), p2(x2, y2); // 创建两个点的对象
cout << calcDistance(p1, p2) << endl; // 友员函数
return 0;
}

输入样例:

输入第1个点的x, y坐标、第2个点的x, y坐标。例如:

3.1 3.1 4.2 4.2

输出样例:

输出两个点的距离(直接使用cout输出,不需要精确到小数点后多少位)。例如:

1.55563

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Point
{
public:
double x,y;
Point(double m_x,double m_y)
{
x=m_x;
y=m_y;
}
friend double calcDistance(Point p1,Point p2);
};
double calcDistance(Point p1,Point p2)
{
return sqrt((p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y));
}

6-5 学校School类的定义

6-5

作者 xyw

单位 惠州学院

请根据main函数及测试需求创建一个学校类。

裁判测试程序样例:

#include<iostream>
using namespace std;

/* 请在这里填写答案 */
int main() {
// 创建一个学校对象,调用无参构造函数
School mySchool;
return 0;
}

输入样例:

在这里给出一组输入。例如:


输出样例:

在这里给出相应的输出。例如:

创建一个学校
撤销一个学校

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class School
{
public:
School(){cout<<"创建一个学校"<<endl;}
~School(){cout<<"撤销一个学校";}
};

十八、2024.5.30——2024春面向对象程序设计作业09

C++-18

(1)单选题

C++-18.1

2-1(C)

在声明类时,下面的说法正确的是( )。

A.可以在类的声明中给数据成员赋初值

B.数据成员的类型可以是register

C.private、public、protected可以按任意顺序出现

D.没有用private、public、protected定义的数据成员是公有成员

2-2(A)

能用友元函数重载的运算符是( )。

A.+

B.=

C.[]

D.->

2-3(B)

关于函数模板,以下说法正确的是( )

A.在函数模板中只能有一个类型参数

B.在template语句与函数模板定义语句之间不允许有别的语句

C.函数模板不可以重载

D.函数模板与同名的非模板函数不可以重载

2-4(A)

vector容器中,( )可以返回vector当前元素的数量。

A.size()

B.capacity()

C.max_size()

D.empty()

2-5(C)

将私有元素和实现操作的内部细节隐藏起来,并能管理自己的内部状态是指对象的( )。

A.模块独立性

B.动态连接性

C.封装性

D.易维护性

2-6(D)

若有下面的语句:

vector<int> v;
for (int i = 0; i < 4; i++)
v.push_back(i + 1);
cout << v.size() << endl;

则执行后程序的输出结果是

A.1

B.2

C.3

D.4

2-7(A)

若派生类的成员函数不能直接访问基类中的某个成员,则该成员一定是基类中的()。

A.私有成员

B.公有成员

C.保护成员

D.私有成员或保护成员

2-8(B)

C++标准输入//输出的头文件是

A.cmath

B.iostream

C.string

D.algorithm

2-9(C)

下列关于虚函数的说法,错误的是_。

A.定义虚函数的关键字是virtual

B.派生类可以重定义基类的虚函数

C.构造函数可以定义为虚函数

D.析构函数可以定义为虚函数

2-10(A)

在子类的成员函数中,可以直接访问的有_

A.父类的public或protected的成员

B.父类的private或protected的成员

C.只有父类的public的成员

D.父类的public或private的成员

(2)程序填空题

C++-18.2

5-1 转换构造函数的应用

C++-5-1

作者 王荣海

单位 泉州师范学院

以下是关于转换构造函数应用的程序,请完成程序填空。

输出结果:
8.8+3.3i
//转换构造函数的应用 
#include<iostream>
using namespace std;
class Complex{
public:
Complex(){ }
Complex(double r,double i)
{ real=r; imag=i;}
Complex(double r){real=r;}
friend Complex operator+(Complex &co1,Complex &co2);
void print();
private:
double real;
double imag;
};
Complex operator+(Complex &co1,Complex &co2) {
Complex temp;
temp.real=co1.real+co2.real;
temp.imag=co1.imag+co2.imag;
return temp;
}
void Complex::print( ) {
cout<<real;
if (imag>0) cout<<"+";
if (imag!=0) cout<<imag<<"i\n";
}
int main( ) {
Complex com1(2.2,3.3),total,com2;
com2=Complex(6.6);
total=com1+com2;
total.print();
return 0;
}

答案:

第一空:

real=r;

第二空:

temp.real=co1.real+co2.real;

第三空:

"+"

第四空:

total=com1+com2;

5-2 类模板的使用

C++-5-2

作者 王荣海

单位 泉州师范学院

以下是关于类模板应用的程序,请完成程序填空。

输入样例:
2 5
3.3 4.5
输出样例:
其中的最大值是:5
其中的最大值是:4.5

//类模板的使用 
#include<iostream>
using namespace std;
template<typename T>
class Compare{
public:
Compare(T a, T b){ x=a; y=b; }
T Max(){ return x>y?x:y; }
private:
T x,y;
};
int main() {
int x,y;
double m,n;
cin>>x>>y;
cin>>m>>n;
Compare<int> com1(x,y);
Compare<double> com2(m,n);
cout<<"其中的最大值是:"<<com1.Max()<<endl;
cout<<"其中的最大值是:"<<com2.Max()<<endl;
return 0;
}

答案:

第一空:

template<typename T>

第二空:

return x>y?x:y;

第三空:

int

第四空:

double

5-3 点类的定义和使用

C++-5-3

作者 GONG

单位 哈尔滨华德学院

已知平面上的一点由其横纵坐标来标识。本题要求按照已给代码和注释完成一个基本的“点”类的定义(坐标均取整型数值)。并通过主函数中的点类对象完成一些简单操作,分析程序运行结果,将答案写在对应的空格中。

#include <iostream>
using namespace std;

class Point
{
private://访问权限设置,私有权限
int x;//横坐标
int y;//纵坐标
public://访问权限设置,公有权限

//以下为构造函数,用参数a,b分别为横纵坐标进行初始化
Point(int a,int b)
{
x=a;
y=b;
}

//以下为拷贝构造函数,借用对象a_point完成初始化
Point(Point &a_point)
{
x=a_point.x;
y=a_point.y;
}

~Point()//以下为析构函数

{
cout<<"Deconstructed Point";
print();
}

//以下为输出点的信息的函数,要求在一行中输出点的坐标信息,形如:(横坐标,纵坐标)
void print()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};


int main()
{
Point b_point(0,0);
b_point.print();
int a,b;
cin>>a>>b;//从标准输入流中提取数值给a,b
Point c_point(a,b);
c_point.print();
return 0;//主函数的返回语句
}
/*设输入为10 10,则本程序的运行结果为:
(0,0)
(10,10)
Deconstructed Point(10,10)
Deconstructed Point(0,0)
*/

答案:

第一空:

iostream

第二空:

private:

第三空:

public:

第四空:

Point

第五空:

x=a

第六空:

y=b

第七空:

Point &

第八空:

~Point()

第九空:

"("<<x<<","<<y<<")"

第十空:

cin>>a>>b;

第十一空:

return 0;

第十二空:

(0,0)

第十三空:

(10,10)

第十四空:

Deconstructed Point(10,10)

第十五空:

Deconstructed Point(0,0)

5-4 引用

C++-5-4

作者 郑远

单位 中国民用航空飞行学院

使用引用作为函数参数

#include<iostream>
using namespace std;
void exchange(int &x,int &y)
{
int temp = x;
x = y;
y = temp;
}

int main(){
int a, b;
cin >> a >> b;
exchange(a, b);
cout << " exchange: " << a << " "<< b << endl;
return 0;
}

答案:

第一空:

int &

第二空:

int &

5-5 知识点3:递增运算符重载

C++-5-5

作者 郑远

单位 中国民用航空飞行学院

#include<iostream>

using namespace std;
class MyInteger {

friend ostream& operator<<(ostream& out, MyInteger myint);

public:
MyInteger() {
m_Num = 0;
}
//前置++
MyInteger operator++() {
//先++
    m_Num++;
//再返回
    return *this;
}

//后置++
    MyInteger operator++(int)
{
//先返回
MyInteger t(*this); //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
m_Num++;
        return t;
}

private:
int m_Num;
};


ostream& operator<<(ostream& out, MyInteger myint) {
out << myint.m_Num;
return out;
}


//前置++ 先++ 再返回
void test01() {
MyInteger myInt;
cout << ++myInt << endl;
cout << myInt << endl;
}

//后置++ 先返回 再++
void test02() {

MyInteger myInt;
cout << myInt++ << endl;
cout << myInt << endl;
}

int main() {

test01();
//test02();

system("pause");

return 0;
}

答案:

第一空:

MyInteger operator++

第二空:

m_Num++;

第三空:

return *this;

第四空:

MyInteger operator++(int)

第五空:

MyInteger t(*this);

第六空:

return t;

(3)函数题

C++-18.3

6-1 你好,getline和string

6-1

作者 向训文

单位 惠州学院

完善程序,从标准输入中读取一行文本(可能包含空格,长度未知),并输出它

裁判测试程序样例:

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

int main() {
string text;
// 请将答案填写在这里
cout << text << endl; // 输出读入的文本
return 0;
}

输入样例:

在这里给出一组输入。例如:

This is Tom.

输出样例:

在这里给出相应的输出。例如:

This is Tom.

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

getline(cin,text);

6-2 你好,输出的格式控制2

6-2

作者 向训文

单位 惠州学院

完善程序:输出两个人的名字,设置宽度为10,填充字符为*

裁判测试程序样例:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() {
string name1, name2;
cin >> name1 >> name2;
// 请将答案填写在这里
return 0;
}

输入样例:

第一行为第一个人的名字,长度不大于10,纯字母

第二行为第二个人的名字,长度不大于10,纯字母

tom  
jerry

输出样例:

在这里给出相应的输出。例如:

*******tom
*****jerry

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

cout<<setw(10)<<setfill('*')<<name1<<endl;
cout<<setw(10)<<setfill('*')<<name2<<endl;

6-3 你好,输出的格式控制(浮点数)

6-3

作者 向训文

单位 惠州学院

完善程序:输出一个浮点数,保留小数点后2位

裁判测试程序样例:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() {
double num;
cin >> num;
// 请将答案填写在这里
return 0;
}

输入样例:

在这里给出一组输入。例如:

3.142

输出样例:

在这里给出相应的输出。例如:

3.14

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

cout<<setiosflags(ios::fixed)<<setprecision(2)<<num;{% endfolding %}

6-4 你好,函数重载2

6-4

作者 向训文

单位 惠州学院

编写两个myMax函数,分别用来计算两个、三个整数的最大值:

裁判测试程序样例:

#include <iostream>
using namespace std;

// 请将答案填写在这里

int main()
{
int x, y, z;
cin >> x >> y >> z;
cout << myMax(x, y) << endl; // 输出前两个数的最大值
cout << myMax(x, y, z) << endl; // 输出三个数的最大值
return 0;
}

输入样例:

输入三个整数。例如:

5 6 12

输出样例:

分别输出前两个数的最大值、三个数的最大值。例如:

6
12

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int myMax(int a,int b,int c)
{
b=a>b?a:b;
b=b>c?b:c;
return b;
}
int myMax(int a,int b)
{return a>b?a:b;}

6-5 学生成绩输出(继承)

6-5

作者 xyw

单位 惠州学院

已知两个类的部分代码如下,请补全Person类的函数定义,并完成Student类的代码编写,使之实现样例的结果。

函数接口定义:

//Person类
class Person{
string m_name; //姓名
public:
Person(string name = "");//构造函数
string getName(); //返回姓名
void show(); //显示姓名
};

//Student类
class Student:public Person{
private:
int m_id; //学号
double m_a, m_b, m_c; //三门课成绩
double m_Avg; //平均成绩

public:
Student(string name = "", int id = ' ', double a = 0,double b = 0,double c = 0);//构造函数
void show(); //显示姓名、学号、三门课成绩、平均成绩 (要求输出时保留两位小数)
double getAvg();//返回平均成绩
};

裁判测试程序样例:

#include <iostream>
#include<string>
#include<iomanip>
using namespace std;
//Person类
class Person{
string m_name; //姓名
public:
Person(string name = "");//构造函数
string getName(); //返回姓名
void show(); //显示姓名
};
class Student:public Person{
private:
int m_id; //学号
double m_a, m_b, m_c; //三门课成绩
double m_Avg; //平均成绩

public:
Student(string name = "", int id = ' ', double a = 0,double b = 0,double c = 0);//构造函数
void show(); //显示姓名、学号、三门课成绩、平均成绩(要求输出时保留两位小数)
double getAvg();//返回平均成绩
};
/* 你的答案嵌入在这里*/

int main(){

Student *s1 = new Student("Zhanghua",11,80,90,100);
s1->show();
cout<<"The average score of "<< s1->getName()<< " is "<<s1->getAvg(); //(要求输出时保留两位小数)

delete s1;
return 0;
}

输入样例:

在这里给出一组输入。例如:


输出样例:

在这里给出相应的输出。例如:

Zhanghua 80 90 100 90.00
The average score of Zhanghua is 90.00

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Person::Person(string name)
{m_name=name;}
string Person::getName()
{return m_name;}
void Person::show()
{cout<<m_name<<" ";}
Student::Student(string name, int id, double a,double b,double c)
:Person(name)
{m_id=id;m_a=a;m_b=b;m_c=c;}
void Student::show()
{
cout<<getName()<<" "<<m_a<<" "<<m_b<<" "<<m_c<<" ";
cout<<setiosflags(ios::fixed)<<setprecision(2)<<(m_a+m_b+m_c)/3<<endl;
}
double Student::getAvg()
{
return (m_a+m_b+m_c)/3;
}

十七、2024.5.27——2024春面向对象程序设计上机练习10

C++-17

(1)程序填空题

C++-17.1

5-1 格式化输出01

C++-5-1

作者 王荣海

单位 泉州师范学院

本题目要求输出两行7890,其中第1行前有3个空格,第2行前没有空格:
(有3个空格)7890
7890

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a=7890;
cout<<setw(7)<<a<<endl;
cout<<a<<endl;
return 0;
}

答案:

第一空:

int a=7890;

第二空:

setw(7)

5-2 模板函数objectSwap的定义

C++-5-2

作者 海洋饼干叔叔

单位 重庆大学

下述程序从控制台读入两个整数,使用objectSwap()函数将其值交换并输出;再从控制台读入两个浮点数,使用objectSwap()函数将其值交换并输出。

请补充objectSwap()模板函数的定义,使程序可以正确运行。

【样例输入】

2 3

1.2 2.1

【样例输出】

after swap(a,b):3,2

after swap(f0,f1):2.1,1.2

#include <iostream>
using namespace std;

//模板函数objectSwap的定义
template<typename T>
void objectSwap(T &a,T &b)
{T x;x=a;a=b;b=x;}
int main(){
int a, b;
cin >> a;
cin >> b;
objectSwap(a,b);
float f0, f1;
cin >> f0;
cin >> f1;
objectSwap(f0,f1);
cout << "after swap(a,b):" << a << "," << b << endl;
cout << "after swap(f0,f1):" << f0 << "," << f1 << endl;
return 0;
}

答案:

第一空:

template<typename T>
void objectSwap(T &a,T &b)
{T x;x=a;a=b;b=x;}

(2)函数题

C++-17.2

6-1 复数的加减运算(运算符重载)

C++-6-1

作者 fpc

单位 内蒙古师范大学

复数加减(运算符重载)

  1. 声明一个复数类CComplex(类私有数据成员为double型的real和image)
  2. 定义构造函数,用于指定复数的实部与虚部。
  3. 重载<<运算符,以格式real+image i的格式输出当前对象(当虚部为非负数时,实部虚部中间用+号连接,当虚部为负数时,实部虚部用-号连接:如3+4i,3-4i,3+0i)。
  4. 重载+运算符,实现两个复数对象之和(实部虚部分别相加)。
  5. 重载-运算符,实现两个复数对象的差(实部虚部分别相减)。

输入格式:
输入有两行:
第一行是复数c1的实部与虚部,以空格分隔;
第二行是复数c2的实部与虚部,以空格分隔。

输出格式:
输出共四行:
第一行是c1;
第二行是c2;
第三行是c1与c2之和;
第四行是c1与c2之差;

函数接口定义:

在这里描述类定义
class CComplex{...}

裁判测试程序样例:

#include <iostream>
using namespace std;

/* 请在这里填写答案 */

int main() {
double r1,r2,i1,i2;
cin>>r1>>i1;
cin>>r2>>i2;
CComplex c1(r1,i1),c2(r2,i2),c3,c4;
cout<<c1;
cout<<c2;
c3=c1+c2;
cout<<c3;
c4=c1-c2;
cout<<c4;
return 0;
}

输入样例:

10 20
30 40

输出样例:

10+20i
30+40i
40+60i
-20-20i

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class CComplex
{
private:
double real,image;
public:
CComplex(double r=0,double i=0)
{
real=r;
image=i;
}
double getreal(){return real;}
double getimage(){return image;}
CComplex operator+(CComplex c)
{
double r,i;
r=real+c.real;
i=image+c.image;
return CComplex(r,i);
}
CComplex operator-(CComplex c)
{
double r,i;
r=real-c.real;
i=image-c.image;
return CComplex(r,i);
}
};
ostream& operator<<(ostream& out,CComplex c)
{
if(c.getimage()>=0)
out<<c.getreal()<<"+"<<c.getimage()<<"i"<<endl;
else
out<<c.getreal()<<c.getimage()<<"i"<<endl;
return out;
}

6-2 你好,getline和string

C++-6-2

作者 向训文

单位 惠州学院

完善程序,从标准输入中读取一行文本(可能包含空格,长度未知),并输出它

裁判测试程序样例:

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

int main() {
string text;
// 请将答案填写在这里
cout << text << endl; // 输出读入的文本
return 0;
}

输入样例:

在这里给出一组输入。例如:

This is Tom.

输出样例:

在这里给出相应的输出。例如:

This is Tom.

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

getline(cin, text);

6-3 你好,输出的格式控制(三角形)

C++-6-3

作者 向训文

单位 惠州学院

完善程序:输入行数rows(大于0),第一行输出rows个*,接下来每行的*个数减1,直到最后一行输出1个*

要求使用setw来控制输出

裁判测试程序样例:

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

int main() {
int rows;
cin >> rows;
// 请将答案填写在这里
return 0;
}

输入样例:

在这里给出一组输入。例如:

6

输出样例:

在这里给出相应的输出。例如:

******
*****
****
***
**
*

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

for(int j=rows;j>0;j--)
{
cout<<setw(j+1)<<setfill('*');
cout<<"\n";
}

十六、2024.5.23——2024春面向对象程序设计作业08

C++-16

(1)单选题

C++-12.1

2-1(D)

假设声明了以下的函数模板:

template
T Max(T x, T y)
{
return (x>y)?x:y;
}
并定义了int i;char c;
错误的调用语句是( )。

A.Max(i,i);

B.Max(c,c);

C.Max((int)c,i);

D.Max(i,c);

2-2(A)

模板的使用是为了( )。

A.提高代码的可重用性

B.提高代码的运行效率

C.加装类的封装性

D.实现多态性

2-3(B)

C++处理异常的机制是由( )3部分组成的。

A.编辑、编译和运行

B.检查、抛出和捕获

C.编辑、编译和捕获

D.检查、抛出和运行

2-4(B)

关于函数模板,以下说法正确的是( )

A.在函数模板中只能有一个类型参数

B.在template语句与函数模板定义语句之间不允许有别的语句

C.函数模板不可以重载

D.函数模板与同名的非模板函数不可以重载

2-5(B)

cout 是由I/O 流库预定义的( )。

A.类

B.对象

C.包含文件

D.常量

2-6(D)

cout 是由I/O 流库预定义的( )。

A.类

B.对象

C.包含文件

D.常量

2-7(D)

下列关于IO流的格式化设置的描述中,错误的是__。

A.在C++中可以人为的控制浮点数的精度

B.width()函数可以用来设置域宽

C.C++系统默认的填充字符为空格

D.这些格式化设置函数都包含在iomanip头文件中

2-8(D)

以下关于异常处理的描述错误的是()。

A.C++程序中出现异常时,编译器不会进行提示

B.将可能产生异常的代码放在try语句块内

C.使用catch关键字接收并处理异常

D.重抛异常可以在try语句块或者catch语句块中调用throw实现

2-9(B)

C++输入流的提取符是( )。

A.//

B.>>

C.<<

D.&

2-10(C)

C++输出流的插入符是( )。

A.//

B.>>

C.<<

D.&

(2)函数题

C++-16.2

6-1 学生成绩的输入和输出(运算符重载)

C++-6-1

作者 何振峰

单位 福州大学

现在需要输入一组学生的姓名和成绩,然后输出这些学生的姓名和等级。

输入时,首先要输入学生数(正整数)N。接着输入N组学生成绩,每组成绩包括两项:第一项是学生姓名,第二项是学生的成绩(整数)。

输出时,依次输出各个学生的序号(从1开始顺序编号),学生姓名,成绩等级(不小于60为PASS,否则为FAIL)

函数接口定义:

面向Student类对象的流插入和流提取运算符

裁判测试程序样例:

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

/* 请在这里填写答案 */

int main(){
int i, repeat;
Student st;
cin>>repeat;
for(i=0;i<repeat;i++){
cin>>st;
cout<<st<<endl;
}
return 0;
}

输入样例:

3
Li 75
Zhang 50
Yang 99

输出样例:

1. Li PASS
2. Zhang FAIL
3. Yang PASS

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

static int xu=0;
class Student
{
public:
int x;
string name;
friend istream &operator >>(istream &in,Student &st);
friend ostream &operator <<(ostream &stream,Student &st);
};
istream &operator>>(istream &in,Student &st)
{
in>>st.name>>st.x;
return in;
}
ostream &operator<<(ostream &stream,Student &st)
{
if(st.x>=60)
stream<<++xu<<". "<<st.name<<" PASS";
if(st.x<60)
stream<<++xu<<". "<<st.name<<" FAIL";
return stream;
}

6-2 求最小值函数模板

C++-6-2

作者 王荣海

单位 泉州师范学院

请定义函数模板Min,实现求两个数的最小值。

程序运行结果为:

the min of i1,i2 is: 15
the min of f1,f2 is: 13.5
the min of d1,d2 is: 50.34
the min of c1,c2 is: m

裁判测试程序样例:

#include<iostream> 
using namespace std;
/* 请在这里填写答案 */
int main( ){
int i1=15, i2=56;
float f1=13.5, f2=24.5;
double d1=50.34, d2=4656.3;
char c1='m',c2='n';
cout<<"the min of i1,i2 is: "<<Min(i1,i2)<<endl;
cout<<"the min of f1,f2 is: "<<Min(f1,f2)<<endl;
cout<<"the min of d1,d2 is: "<<Min(d1,d2)<<endl;
cout<<"the min of c1,c2 is: "<<Min(c1,c2)<<endl;
return 0;
}

输入样例:

无

输出样例:

the min of i1,i2 is: 15
the min of f1,f2 is: 13.5
the min of d1,d2 is: 50.34
the min of c1,c2 is: m

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

template <typename T>
T Min(T x,T y)
{
return x<y?x:y;
}

6-3 异常处理(除法错误)

C++-6-3

作者 王荣海

单位 泉州师范学院

下面是这个程序处理除数错误的异常,在函数 Div( )中抛出一个除数错误的异常,并在main函数中的 catch 块中捕获该异常。

函数接口定义:

double Div(int x, int y);

裁判测试程序:

#include <iostream>
using namespace std;
/* 请在这里填写答案 */
int main ()
{
int a,b;
double c = 0;
cin>>a>>b;
try {
c = Div(a, b);
cout << c << endl;
}catch (const char* message) {
cout << message << endl;
}
return 0;
}

输入样例:

5 0

输出样例:

除数不能为0!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

double Div(int x, int y)
{
if(y==0)
throw "除数不能为0!";
double x1=x,y1=y,s=x1/y1;
return s;
}

6-4 你好,异常

C++-6-4

作者 向训文

单位 惠州学院

完善函数time2sec的定义,使得程序正确运行:

裁判测试程序样例:

#include <iostream>
using namespace std;

// 请将答案填写在这里

int main() {
int hour, minute, second;
cin >> hour >> minute >> second; // 输入做某件事件花费的总时长
try {
cout << time2sec(hour, minute, second); // 将时间转成总的秒数
} catch (const char *error) { // 当输入的小时数、分钟数或秒数小于0时,抛出异常字符串"bad time"
cout << error << endl;
}
return 0;
}

输入样例:

在这里给出一组输入。例如:

1 1 1

输出样例:

在这里给出相应的输出。例如:

3661

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int time2sec(int h,int m,int s)
{
if(h<0||m<0||s<0)
throw "bad time";
return h*3600+m*60+s;
}

十五、2024.5.16——2024春面向对象程序设计上机练习09

C++-15

(1)程序填空题

C++-15.1

5-1 类模板的使用

C++-5-1

作者 王荣海

单位 泉州师范学院

以下是关于类模板应用的程序,请完成程序填空。

输入样例:
2 5
3.3 4.5
输出样例:
其中的最大值是:5
其中的最大值是:4.5

//类模板的使用 
#include<iostream>
using namespace std;
template<typename T>
class Compare{
public:
Compare(T a, T b){ x=a; y=b; }
T Max(){return x>y?x:y;}
private:
T x,y;
};
int main() {
int x,y;
double m,n;
cin>>x>>y;
cin>>m>>n;
Compare<int> com1(x,y);
Compare<double> com2(m,n);
cout<<"其中的最大值是:"<<com1.Max()<<endl;
cout<<"其中的最大值是:"<<com2.Max()<<endl;
return 0;
}

答案:

第一空:

template<typename T>

第二空:

return x>y?x:y;

第三空:

int

第四空:

double

5-2 模板函数objectSwap的定义

C++-5-1

作者 海洋饼干叔叔

单位 重庆大学

下述程序从控制台读入两个整数,使用objectSwap()函数将其值交换并输出;
再从控制台读入两个浮点数,使用objectSwap()函数将其值交换并输出。

请补充objectSwap()模板函数的定义,使程序可以正确运行。

【样例输入】

2 3

1.2 2.1

【样例输出】

after swap(a,b):3,2

after swap(f0,f1):2.1,1.2

#include <iostream>
using namespace std;

//模板函数objectSwap的定义
template<typename T>
void objectSwap(T &a,T &b)
{T x;x=a;a=b;b=x;}
int main(){
int a, b;
cin >> a;
cin >> b;
objectSwap(a,b);
float f0, f1;
cin >> f0;
cin >> f1;
objectSwap(f0,f1);
cout << "after swap(a,b):" << a << "," << b << endl;
cout << "after swap(f0,f1):" << f0 << "," << f1 << endl;
return 0;
}

答案:

第一空:

template<typename T>
void objectSwap(T &a,T &b)
{T x;x=a;a=b;b=x;}

(2)函数题

C++-15.2

6-1 求最小值函数模板

C++-6-1

作者 王荣海

单位 泉州师范学院

请定义函数模板Min,实现求两个数的最小值。

程序运行结果为:

the min of i1,i2 is: 15
the min of f1,f2 is: 13.5
the min of d1,d2 is: 50.34
the min of c1,c2 is: m

裁判测试程序样例:

#include<iostream> 
using namespace std;
/* 请在这里填写答案 */
int main( ){
int i1=15, i2=56;
float f1=13.5, f2=24.5;
double d1=50.34, d2=4656.3;
char c1='m',c2='n';
cout<<"the min of i1,i2 is: "<<Min(i1,i2)<<endl;
cout<<"the min of f1,f2 is: "<<Min(f1,f2)<<endl;
cout<<"the min of d1,d2 is: "<<Min(d1,d2)<<endl;
cout<<"the min of c1,c2 is: "<<Min(c1,c2)<<endl;
return 0;
}

输入样例:

无

输出样例:

the min of i1,i2 is: 15
the min of f1,f2 is: 13.5
the min of d1,d2 is: 50.34
the min of c1,c2 is: m

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

template<typename T>
T Min(T a,T b)
{
return a<b?a:b;
}

6-2 包括求最小值成员函数的类模板

C++-6-2

作者 王荣海

单位 泉州师范学院

请定义类模板Classmin,其中有成员函数Min,用来求两个数据的最小值。

程序运行结果如下:

其中的最小值是:6
其中的最小值是:2.34
其中的最小值是:c

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:
#include<iostream>
using namespace std;
/* 请在这里填写答案 */
int main() {
Classmin<int> com1(6,9);
Classmin<double> com2(2.34,3.78);
Classmin<char> com3('c','y');
cout<<"其中的最小值是:"<<com1.Min()<<endl;
cout<<"其中的最小值是:"<<com2.Min()<<endl;
cout<<"其中的最小值是:"<<com3.Min()<<endl;
return 0;
}

输入样例:

无

输出样例:

其中的最小值是:6
其中的最小值是:2.34
其中的最小值是:c

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

template<typename T>
class Classmin
{
private:
T x,y;
public:
Classmin(T a,T b):x(a),y(b){}
T Min()
{
return x<y?x:y;
}
};

6-3 你好,类模板(圆的面积)

C++-6-3

作者 向训文

单位 惠州学院

完善Square的定义,使得程序正确运行:

裁判测试程序样例:

#include <iostream>
using namespace std;

// 请将答案填写在这里

int main() {
int width1;
cin >> width1; // 输入正方形的边长
Square<int> square1(width1);
cout << square1.getArea() << endl; // 输出正方形的面积

double width2;
cin >> width2; // 输入正方形的边长
Square<double> square2(width2);
cout << square2.getArea() << endl; // 输出正方形的面积

return 0;
}

输入样例:

在这里给出一组输入。例如:

3
1.1

输出样例:

在这里给出相应的输出。例如:

9
1.21

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

template<typename T>
class Square
{
private:
T x;
public:
Square(T a):x(a){}
T getArea()
{return x*x;}
};

十四、2024.5.13——2024春面向对象程序设计上机练习08

C++-14

(1)程序填空题

C++-14.1

5-1 抽象类和纯虚函数的使用

C++-5-1

作者 李廷元

单位 中国民用航空飞行学院

下面的程序定义了Base1类、Base2类和Derived类。

Base1是一个抽象类,其类体中声明了纯虚函数Show。

Base2类的构造函数负责动态分配一个字符数组,并将形参指向的字符串复制到该数组中,复制功能要求通过调用strcpy函数来实现。

Derived类以公有继承方式继承Base1类,以私有继承方式继承Base2类。在Derived类的构造函数的成员初始化列表中调用Base类的构造函数。

请在空白地方填写适当代码,以完成Base1、Base2和Derived类的功能。

此程序的正确输出结果应为:

I’m a derived class.

#include <iostream>
#include <cstring>
using namespace std;
class Base1 {
public:
//下列语句需要声明纯虚函数Show
virtual void Show()=0;
};

class Base2 {
protected:
char * _p;
Base2(const char *s)
{
_p = new char[strlen(s) + 1];
//下列语句将形参指向的字符串常量复制到该类的字符数组中
strcpy(_p,s);
}
~Base2() { delete [] _p; }
};

//Derived类公有继承Base1,私有继承Base2类
class Derived : public Base1,public Base2 {
public:
//以下构造函数调用Base2类构造函数
Derived(const char *s) : Base2(s)
{ }
void Show()
{ cout << _p << endl; }
};

int main()
{
Base1 *pb = new Derived("I'm a derived class.");
pb->Show();
delete pb;
return 0;
}

答案:

第一空:

virtual void Show()=0

第二空:

strcpy(_p,s)

第三空:

public Base1,public Base2

第四空:

Base2(s)

5-2 动物和狗 - 《C++编程基础及应用》- 习题15-2

C++-5-1

作者 海洋饼干叔叔

单位 重庆大学

请将后续代码补充完整,使其满足下述要求,并可得到期望的运行结果。

  • 设计动物基类Animal,包括体重、脚的数量等数据成员;

  • 从Animal扩展出子类Dog,添加名字等数据成员;

  • 为两个类添加带有信息输出的构造函数以及析构函数,观察当一个Dog对象被创建时,子类与父类构造函数的执行顺序;

  • 观察当一个Dog对象被析构时,子类与父类析构函数的执行顺序;

  • 打印输出一个Dog对象的地址以及子类对象中父对象的地址,分析Dog对象的内存结构。

    #include <iostream>
    using namespace std;
    class Animal {
    public:
    int iFeetCount {0};
    int iWeight=0;
    Animal(){
    cout << "Animal(), weight = " << iWeight << endl;
    }
    ~Animal()
    {
    cout << "~Animal(), weight = " << iWeight << endl;
    }
    };

    class Dog : public Animal {
    public:
    string sName;
    Dog(const string name, int weight){
    sName = name;
    iFeetCount = 4;
    iWeight=weight;
    cout <<"Dog(), name = " << name << ", weight = " << iWeight << endl;
    }
    ~Dog()
    {
    cout <<"~Dog(), name = " << sName << ", weight = " << iWeight << endl;
    }
    };
    int main()
    {
    Dog* d1 = new Dog("Bottle",3100);
    delete d1;
    cout << "---------------------------------------" << endl;

    Dog* d2 = new Dog("Nauty",2312);

    Animal* a2 = d2;
    if (a2==d2){
    cout << "Parent object is located at the beginning of sub object." << endl;
    }
    delete d2;

    return 0;
    }

期望的运行结果为:

Animal(), weight = 0
Dog(), name = Bottle, weight = 3100
~Dog(), name = Bottle, weight = 3100
~Animal(), weight = 3100
---------------------------------------
Animal(), weight = 0
Dog(), name = Nauty, weight = 2312
Parent object is located at the beginning of sub object.
~Dog(), name = Nauty, weight = 2312
~Animal(), weight = 2312

答案:

第一空:

int iWeight=0;

第二空:

cout << "Animal(), weight = " << iWeight << endl;

第三空:

~Animal()

第四空:

public Animal

第五空:

iWeight=weight;

第六空:

~Dog()

(2)函数题

C++-14.2

6-1 应用虚函数计算三角形、矩形的面积

C++-6-1

作者 王荣海

单位 泉州师范学院

以下程序应用虚函数计算三角形、矩形的面积;
输入两行,每行两个数,两个数之间用空格隔开;
第一行两个数表示三角形的底和高(顺序可任意);
第二行两个数表示矩形的长和宽(顺序可任意);
输出三角形与矩形的面积;
任何输入的数据小于或等于0,输出“input invalid!”提示;
输入输出具体详见下面的输入、输出样例;
以下程序代码已经实现Figure类和main函数(main函数有部分注释说明);
请编写表示三角形的类Triangle和矩形的类Square

类编写说明:

Figure和Triangle类代码插入到下面程序的请在这里编写代码的注释语句位置

裁判测试程序样例:

#include  <iostream>
using namespace std;
class Figure {
protected:
double x,y;
public:
Figure(double a,double b){ x=a;y=b; }
virtual void area()
{cout<<"在基类中定义的虚函数\n";}
};
/* 请在这里编写代码 */
int main( ) {
Figure *p; //定义基类指针p
double x,y; //x,y分别表示三角形的底和高
double a,b; //a,b分别表示矩形的长和宽
cin>>x>>y;
cin>>a>>b;
Triangle t(x,y); //定义三角形类对象t
Square s(a,b); //定义矩形类对象s
p=&t; p->area();
p=&s; p->area();
return 0;
}

输入样例1:

10 6
20 6

输出样例1:

Triangle area:30
Square area:120

输入样例2:

15 0
12 15

输出样例2:

input invalid!
Square area:180

输入样例3:

12 15
13 -2

输出样例3:

Triangle area:90
input invalid!

输入样例4:

-3 2
3 -2

输出样例4:

input invalid!
input invalid!

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Triangle:public Figure
{
public:
Triangle(int x1,int y1):Figure(x1,y1){}
void area()
{
if(x<=0||y<=0)
cout<<"input invalid!"<<endl;
else
cout<<"Triangle area:"<<x*y/2<<endl;
}
};
class Square:public Figure
{
public:
Square(int x1,int y1):Figure(x1,y1){}
void area()
{
if(x<=0||y<=0)
cout<<"input invalid!"<<endl;
else
cout<<"Square area:"<<x*y<<endl;
}
};

6-2 Shape抽象类

C++-6-2

作者 fpc

单位 内蒙古师范大学

请根据程序的输出结果,重载类A的+和-运算符。

已知抽象类类Shape定义如下,其中两个纯虚函数分别为计算面积getArea()和计算周长getPerim()。请通过Shape类派生出矩形类Rectangle和圆类Circle,计算各自的面积和周长,并能够按照main函数给出的测试代码完成给定的输入。

Shape类定义及测试程序如下:

#include <iostream>
using namespace std;
const double PI=3.14;
class Shape {
public:
virtual double getArea()=0;
virtual double getPerim()=0;
};

/*请在这里输入你的代码*/

int main(){
double r,l,w;
cin>>r;
cin>>l>>w;
Shape *p=NULL;
p=new Circle(r);
print(p);//输出圆面积与周长
p=new Rectangle(l,w);
print(p);//输出矩形面积与周长
return 0;
}

输入样例:

1 2 3

输出样例:

Area:3.14
Perimeter:6.28
Area:6
Perimeter:10

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Circle:public Shape
{
private:
double m_r;
public:
Circle(int x){m_r=x;}
double getArea()
{return m_r*m_r*PI;}
double getPerim()
{return m_r*2*PI;}
friend void print(Circle *p);
};
class Rectangle:public Shape
{
private:
double m_c,m_k;
public:
Rectangle(int x,int y){m_c=x;m_k=y;}
double getArea()
{return m_c*m_k;}
double getPerim()
{return 2*(m_c+m_k);}
friend void print(Rectangle *p);
};
void print(Shape *p)
{
cout<<"Area:"<<p->getArea()<<endl;
cout<<"Perimeter:"<<p->getPerim()<<endl;
}

6-3 你好,虚析构函数

C++-6-3

作者 向训文

单位 惠州学院

请完善Pet类的定义,使程序正确运行:

裁判测试程序样例:

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

// 请将答案填写在这里

// 构造函数的实现已经写在这里,只需要在类的定义时添加声明
Pet::Pet(const string &name): m_name(name) {}

// 析构函数的实现已经写在这里,只需要在类的定义时添加声明
Pet::~Pet() { cout << "destroy pet: " << m_name << endl; }

class Dog: public Pet {
public:
Dog(const string &name): Pet(name) {}
~Dog() { cout << "destroy dog: " << m_name << endl; }
};

int main() {
string name;
cin >> name;
Pet *pet = new Dog(name);
delete pet;
return 0;
}

输入样例:

在这里给出一组输入。例如:

tom

输出样例:

在这里给出相应的输出。例如:

destroy dog: tom
destroy pet: tom

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Pet
{
public:
string m_name;
Pet(const string &name);
virtual ~Pet();
};

十三、2024.4.28——2024春面向对象程序设计上机练习07

C++-13

(1)程序填空题

C++-13.1

5-1 知识点1:加号运算符重载

C++-5-1

作者 郑远

单位 中国民用航空飞行学院

#include<iostream>
using namespace std;
class Person {
public:
Person() {};
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
//成员函数实现 + 号运算符重载
Person operator+(const Person& p) {
Person temp;
temp.m_A=p.m_A+m_A;
temp.m_B=p.m_B+m_B;
return temp;
}
int m_A;
int m_B;
};
//运算符重载 可以发生函数重载
Person operator+(const Person& p2, int val)
{
Person temp;
temp.m_A=p2.m_A+val;
    temp.m_B=p2.m_B+val;
return temp;
}
void test() {
Person p1(10, 10);
Person p2(20, 20);
//成员函数方式
Person p3 = p2 + p1; //相当于 p2.operaor+(p1)
cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;
Person p4 = p3 + 10; //相当于 operator+(p3,10)
cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
}
int main() {
test();
return 0;
}

答案:

第一空:

temp.m_A=p.m_A+m_A;

第二空:

temp.m_B=p.m_B+m_B;

第三空:

Person operator+

第四空:

temp.m_A=p2.m_A+val;

第五空:

temp.m_B=p2.m_B+val;

(2)函数题

C++-13.2

6-1 复数类重载加法、减法和乘法运算符

C++-6-1

作者 傅尔胜

单位 郑州航空工业管理学院

以下定义了一个复数类及其部分实现,现要求将类的构造函数以及运算符+、- 和 * 函数重载补充完整。

复数类定义:

在这里描述复数类定义。具体如下:
class complex {
public:
complex(float r=0,float i=0); // 构造函数
complex operator+(const complex &op2) const; //重载运算符 +
complex operator-(const complex &op2) const; //重载运算符 -
complex operator*(const complex &op2) const; //重载运算符 *
void display() const; // 按数学写法输出复数
private:
float real;
float imag;
};

裁判测试程序样例:

在这里给出复数类测试的例子。例如:
#include <iostream>
using namespace std;
class complex {
public:
complex(float r=0,float i=0); // 构造函数
complex operator+(const complex &op2) const; //重载运算符 +
complex operator-(const complex &op2) const; //重载运算符 -
complex operator*(const complex &op2) const; //重载运算符 *
void display() const; // 按数学写法输出复数
private:
float real;
float imag;
};


/* ------------------- 请在这里填写答案-------------------- */


void complex::display() const {
if(real&&imag)
if(imag==1||imag==-1)
cout<<real<<(imag>0?"+":"-")<<"i"<<endl;
else
cout<<real<<(imag>0?"+":"")<<imag<<"i"<<endl;
else if(real)
cout<<real<<endl;
else if (imag)
if(imag==1||imag==-1)
cout<<(imag>0?"":"-")<<"i"<<endl;
else
cout<<imag<<"i"<<endl;
else
cout<<0<<endl;
}

int main() {
double real,imag;
complex c,d,e;

cin>>real>>imag;
complex c1(real,imag);
cin>>real>>imag;
complex c2(real,imag);

c=c1+c2;
d=c1-c2;
e=c1*c2;
c.display() ;
d.display() ;
e.display();

return 0;
}

输入样例:

在这里给出一组输入。例如:

2 3
-4 -5

输出样例:

在这里给出相应的输出。例如:

-2-2i
6+8i
7-22i

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

complex::complex(float r,float i)
{
real=r;
imag=i;
}
complex complex::operator+(const complex &op2) const
{
complex t;
t.real=real+op2.real;
t.imag=imag+op2.imag;
return t;
}
complex complex::operator-(const complex &op2) const
{
complex t;
t.real=real-op2.real;
t.imag=imag-op2.imag;
return t;
}
complex complex::operator*(const complex &op2) const
{
complex t;
t.real=real*op2.real-imag*op2.imag;
t.imag=real*op2.imag+imag*op2.real;
return t;
}

6-2 重载+-运算符

C++-6-2

作者 李廷元

单位 中国民用航空飞行学院

请根据程序的输出结果,重载类A的+和-运算符。

类和函数接口定义:

class A {
public:
A(int x = 0, int y = 0) : x(x), y(y) {}
void show() const;
A operator+(A& a); //重载+运算符
A operator-(A& a); //重载-运算符
private:
int x, y;
};

裁判测试程序样例:

#include <iostream>
using namespace std;

class A {
public:
A(int x = 0, int y = 0) : x(x), y(y) {}
void show() const;
A operator+(A& a);
A operator-(A& a);
private:
int x, y;
};

void A::show() const {
cout << "(x,y) = " << "(" << x << "," << y << ")" << endl;
}

/* 请在这里填写答案 */

int main() {
A a1(1, 2);
A a2(4, 5);
A a;
cout << "a1:"; a1.show();
cout << "a2:"; a2.show();
a = a1 + a2;
cout << "a:"; a.show();
a = a1 - a2;
cout << "a:"; a.show();
return 0;
}

输入样例:

本题无输入。

输出样例:

a1:(x,y) = (1,2)
a2:(x,y) = (4,5)
a:(x,y) = (5,7)
a:(x,y) = (-3,-3)

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

A A::operator+(A& a)
{
A t;
t.x=x+a.x;
t.y=y+a.y;
return t;
}
A A::operator-(A& a)
{
A t;
t.x=x-a.x;
t.y=y-a.y;
return t;
}

6-3 你好,友员运算符重载函数

C++-6-3

作者 向训文

单位 惠州学院

已知Point类的定义,完善友员运算符重载函数的定义,使得程序正确运行。
假设两个点相减的实现为:x坐标相减,y坐标相减;

假设一个点取负的实现为:x坐标取负,y坐标取负;

裁判测试程序样例:

#include<iostream>
using namespace std;

class Point {
public:
Point(double x = 0.0, double y = 0.0): m_x(x), m_y(y) {}
void print() const { cout << m_x << ", " << m_y << endl; }
friend Point operator-(const Point &p1, const Point &p2);
friend Point operator-(const Point &p);
private:
double m_x, m_y;
};

// 答案请写在这里

int main() {
double x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Point p1(x1, y1), p2(x2, y2), p3;
p3 = p1 - p2;
p3.print();
p3 = -p3;
p3.print();
return 0;
}

输入样例:

在这里给出一组输入。例如:

2.2 2.2
1.1 1.1

输出样例:

在这里给出相应的输出。例如:

1.1, 1.1
-1.1, -1.1

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Point operator-(const Point &p1, const Point &p2)
{
Point t;
t.m_x=p1.m_x-p2.m_x;
t.m_y=p1.m_y-p2.m_y;
return t;
}
Point operator-(const Point &p) 
{
Point t;
t.m_x=-1*p.m_x;
t.m_y=-1*p.m_y;
return t;
}

十二、2024.4.25——024春面向对象程序设计作业06

C++-12

(1)单选题

C++-12.1

2-1(C)

在C++语言中设置虚基类的目的是( ) 。

A.简化程序代码

B.提高程序的运行效率

C.解决多继承造成的二义性问题

D.缩短程序的目标代码

2-2(C)

关于赋值兼容关系

已知 BASE 为基类,DERIVED 为公有派生类,有下面的函数声明

void F(BASE *p);
void G(DERIVED *p);

若 a 为基类对象,b 为派生类对象,则 ▁▁▁▁▁ 是错误的用法。

A.F(&a)

B.F(&b)

C.G(&a)

D.G(&b)

2-3(A)

对含有对象成员的派生类的构造函数和析构函数的描述中,以下错误的是( )。

A.创建派生类对象时,基类的构造函数最迟被执行

B.创建派生类对象时,内嵌对象成员的构造函数比派生类的构造函数更早执行

C.撤消派生类对象时,派生类的析构函数最先被执行

D.撤消派生类对象时,基类的构造函数最迟被执行

2-4(C)

在C++中,关于派生类访问基类成员的说法,以下哪项是正确的?

A.派生类可以直接访问基类的所有成员

B.派生类只能访问基类的公有(public)成员

C.派生类可以访问基类的公有(public)和保护(protected)成员,但不能访问私有(private)成员

D.派生类无法访问基类的任何成员

2-5(C)

在C++中,关于基类私有成员在派生类中的表现和可访问性,以下说法正确的是 __

A.派生类可以直接访问继承自基类的私有成员

B.派生类无法继承基类的私有成员

C.派生类可以继承基类的私有成员,但无法直接访问它们

D.派生类需要通过特定的访问修饰符才能继承基类的私有成员

(2)程序填空题

C++-12.2

5-1 动物和狗 - 《C++编程基础及应用》- 习题15-2

作者 海洋饼干叔叔

单位 重庆大学

请将后续代码补充完整,使其满足下述要求,并可得到期望的运行结果。

  • 设计动物基类Animal,包括体重、脚的数量等数据成员;

  • 从Animal扩展出子类Dog,添加名字等数据成员;

  • 为两个类添加带有信息输出的构造函数以及析构函数,观察当一个Dog对象被创建时,子类与父类构造函数的执行顺序;

  • 观察当一个Dog对象被析构时,子类与父类析构函数的执行顺序;

  • 打印输出一个Dog对象的地址以及子类对象中父对象的地址,分析Dog对象的内存结构。

#include <iostream>
using namespace std;
class Animal {
public:
int iFeetCount {0};
int iWeight=0;
Animal(){
cout<<"Animal(), weight = "<<iWeight<<endl;
}
~Animal() {
cout << "~Animal(), weight = " << iWeight << endl;
}
};
class Dog : public Animal {
public:

string sName;
Dog(const string name, int weight){
sName = name;
iFeetCount = 4;
iWeight=weight;
cout <<"Dog(), name = " << name << ", weight = " << iWeight << endl;
}

~Dog(){
cout <<"~Dog(), name = " << sName << ", weight = " << iWeight << endl;
}

};
int main()
{

Dog* d1 = new Dog("Bottle",3100);
delete d1;

cout << "---------------------------------------" << endl;

Dog* d2 = new Dog("Nauty",2312);

Animal* a2 = d2;
if (a2==d2){
cout << "Parent object is located at the beginning of sub object." << endl;
}
delete d2;

return 0;

}

期望的运行结果为:

Animal(), weight = 0
Dog(), name = Bottle, weight = 3100
~Dog(), name = Bottle, weight = 3100
~Animal(), weight = 3100
---------------------------------------
Animal(), weight = 0
Dog(), name = Nauty, weight = 2312
Parent object is located at the beginning of sub object.
~Dog(), name = Nauty, weight = 2312
~Animal(), weight = 2312

答案:

第一空:

int iWeight=0;

第二空:

cout<<"Animal(), weight = "<<iWeight<<endl;

第三空:

~Animal()

第四空:

public Animal

第五空:

iWeight=weight;

第六空:

~Dog()

(3)函数题

C++-12.3

6-1 虚基类构造函数执行顺序

6-1

作者 王荣海

单位 泉州师范学院

以下程序的运行结果是:
class base1
class base2
class level1
class base2
class level2
class toplevel

请编写toplevel类代码

函数接口定义:

toplevel类代码插入到下面程序的注释语句位置

裁判测试程序样例:

#include <iostream>
using namespace std;
class base1{
public:
base1()
{
cout<<"class base1"<<endl;
}
};
class base2{
public:
base2()
{
cout<<"class base2"<<endl;
}
};
class level1:public base2,virtual public base1{
public:
level1()
{
cout<<"class level1"<<endl;
}
};
class level2:public base2,virtual public base1{
public:
level2()
{
cout<<"class level2"<<endl;
}
};
/* 请在这里编写代码 */
int main() {
toplevel obj;
return 0;
}

输入样例:

无

输出样例:

class base1
class base2
class level1
class base2
class level2
class toplevel

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class toplevel:public level1,public level2
{
public:
toplevel()
{
cout<<"class toplevel"<<endl;
}
};

6-2 虚基类的应用-人与教师学生

6-2

作者 范鹏程

单位 内蒙古师范大学

派生类定义:根据所给的基类,完成多重继承下的派生类定义
函数接口定义:

#include <iostream>
#include <string>
using namespace std;
//定义公共基类Person
class Person
{public:
Person(string nam,char s,int a)
{name=nam;sex=s;age=a;}
protected:
string name;
char sex;
int age;
};
//定义类Teacher
class Teacher:virtual public Person
{public:
Teacher(string nam,char s,int a,string t):Person(nam,s,a)
{title=t;
}
protected:
string title;
};
//定义类Student
class Student:virtual public Person
{public:
Student(string nam,char s,int a,float sco):
Person(nam,s,a),score(sco){}
protected:
float score;
};

/*这里添加派生类的定义*/

裁判测试程序样例:

int main( )
{Graduate grad1("Wang-li",'f',24,"assistant",89.5,1234.5);
grad1.show( );
return 0;
}

输出样例:

在这里给出相应的输出。例如:

name:Wang-li
age:24
sex:f
score:89.5
title:assistant
wages:1234.5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Graduate :public Teacher, public Student
{
public:
Graduate(string nam, char s, int a, string t, float sco, float wa) :Person(nam,s,a),Teacher(nam,s,a,t), Student(nam,s,a,sco)
{
wages = wa;
}
float wages;
void show()
{
cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "sex:" << sex << endl;
cout << "score:" << score << endl;
cout << "title:" << title << endl;
cout << "wages:" << wages << endl;
}
};

6-3 沙发床-虚基类

6-3

作者 fpc

单位 内蒙古师范大学

根据给出的Furniture类以及SleeperSofa类,定义SleeperSofa继承时的父类Bed和Sofa

Furniture 类与测试程序的定义如下:

#include<iostream>
using namespace std;

class Furniture
{
protected:
int weight ;
public:
Furniture(){}
void setWeight( int i ){ weight= i ;}
int getWeight() { return weight; }
};

/* 请在这里填写答案 */

class SleeperSofa :public Bed,public Sofa
{
public:
SleeperSofa() {}
void foldout()
{
cout<<"Fold out sleepersofa"<<endl;
}
};
int main()
{
SleeperSofa ss;
ss.setWeight(20);
cout<< ss.getWeight()<<endl;
ss.sleep();
ss.watchTV();
ss.foldout();
return 0;
}

输入样例:

无

输出样例:

在这里给出相应的输出。例如:

20
Sleeping
Watching TV
Fold out sleepersofa

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Sofa:virtual public Furniture
{
public:
Sofa(){}
void sleep()
{cout<<"Sleeping"<<endl;}
};
class Bed:virtual public Furniture
{
public:
Bed(){}
void watchTV()
{cout<<"Watching TV"<<endl;}
};

6-4 鸭子也是鸟

6-4

作者 fpc

单位 内蒙古师范大学

按要求完成下面的程序:

1、定义一个Bird类,包含一个void类型的无参的speak方法,输出“Jiu-Jiu-Jiu”。

2、定义一个Duck类,公有继承自Bird类,其成员包括:

(1)私有string类型的成员name;

(2)带参数的构造函数,用指定形参对私有数据成员进行初始化;

(3)公有的成员函数printName,无形参,void类型,功能是输出成员name的值,具体输出格式参见main函数和样例输出。

裁判测试程序样例:

#include <iostream>#include <string>using namespace std;/* 请在这里填写答案 */int main(){    Bird b;    b.speak();    Duck d("Donald"); //定义派生类对象    d.printName();    //派生类对象使用本类成员函数    d.speak();    //派生类对象使用基类成员函数    return 0;}

输入样例:

无输入

输出样例:
Jiu-Jiu-Jiu
Dird Name:Donald
Jiu-Jiu-Jiu

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Bird
{
public:
void speak()
{cout<<"Jiu-Jiu-Jiu"<<endl;}
};
class Duck:public Bird
{
private:
string name;
public:
Duck(string b_name)
{name=b_name;}
string get_name()
{return name;}
void printName()
{cout<<"Dird Name:"<<get_name()<<endl;}
};

十一、2024.4.11——2024春面向对象程序设计上机练习06

C++-11

(1)程序填空题

C++-11.1

5-1 多继承练习

C++-5-1

作者 王荣海

单位 泉州师范学院

以下是多继承相关的程序,请完成程序填空。

输入样例: 100 200 300
输出样例: Constructor X1.
Constructor X2.
Constructor A.
100
200
300
#include <iostream>
using namespace std;
class X1{
public:
X1(int i)
{
x1=i;
cout<<"Constructor X1. "<<endl;
}
void print ()
{
cout<<x1<<endl;
}
private:int x1;
};
class X2{
public:
X2(int i)
{
x2=i;
cout<<"Constructor X2. "<<endl;
}
void print ()
{
cout<<x2<<endl;
}
private:int x2;
};
class A:public X1,public X2{
public:
A(int i,int j,int l);
void print();
private:
int a;
};
A::A(int i,int j,int l):X1(i),X2(j)
{
a=l;
cout<<"Constructor A. "<<endl;
}
void A::print()
{
X1::print();
X2::print();
cout<<a<<endl;
}
int main() {
int m,n,k;
cin>>m>>n>>k;
A aa(m,n,k);
aa.print();
return 0;
}

答案:

第一空:

X1(int i)

第二空:

X2(int i)

第三空:

A(int i,int j,int l);

第四空:

int m,n,k;

第五空:

A(int i,int j,int l);

5-2 访问声明的应用

C++-5-2

作者 王荣海

单位 泉州师范学院

以下是关于访问声明应用的程序,请完成程序填空。

输入样例:
100
输出样例:
a=100


#include<iostream>
using namespace std;
class A{
int x;
public:
A(int x1){x=x1;}
void show(){cout<<"x="<<x;}
void show(int a){cout<<"a="<<a;}
};
class B: private A{
int y;
public:
B(int x1,int y1):A(x1){y=y1;}
void show(int n){A::show(n);}
};
int main() {
int a;
cin>>a;
B b(10,20);
b.show(a);;
return 0;
}

答案:

第一空:

int a

第二空:

void show(int n){A::show(n);}

第三空:

show(a);

(2)函数题

C++-11.2

6-1 显示姓名、出生日期及出生时间

C++-6-1

作者 王荣海

单位 泉州师范学院

本程序已经给出main函数,类Time和Date类分别表示小孩的出生时间和出生日期,要求设计一个派生类Birthtime,它继承类Time和Date,并且增加一个数据成员Childname用于表示小孩的名字

派生类Birthtime 接口定义:

class Birthtime{ //补充继承说明 
    public:
        //公有成员
    private:
        //私有成员
};

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;
class Time{
public:
Time(int h,int m,int s)
{
hours=h;
minutes=m;
seconds=s;
}
void display()
{
cout<<"出生时间:"<<hours<<"时"<<minutes<<"分"<<seconds<<"秒"<<endl;
}
protected:
int hours,minutes,seconds;
};
class Date{
public:
Date(int m,int d,int y)
{
month=m;
day=d;
year=y;
}
void display()
{
cout<<"出生日期:"<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
}
protected:
int month,day,year;
};
/* 请在这里填写答案 */
int main() {
int dm,dd,dy,th,tm,ts;
string name;
cin>>dm>>dd>>dy>>th>>tm>>ts>>name;
Birthtime B1(dm,dd,dy,th,tm,ts,name);
B1.display();
return 0;
}

输入样例:

请输入6个整数和1个字符串,6个整数分别表示月、日、年、时、分、秒,1个字符串表示姓名。

12 15 2003 12 15 13 张三

输出样例:

在这里给出相应的输出。例如:

小孩的姓名是:张三
小孩的出生日期和出生时间分别为:
出生日期:2003年12月15日
出生时间:12时15分13秒

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Birthtime:public Time,public Date{  //补充继承说明
public:
Birthtime(int h,int m,int s,int c,int d,int y,string ch):Date(h,m,s),Time(c,d,y)
{Childname=ch;}//公有成员
string getname()
{return Childname;}
void display()
{
cout<<"小孩的姓名是:"<<getname()<<endl;
cout<<"小孩的出生日期和出生时间分别为:"<<endl;
Date::display();
Time::display();
}
private:
string Childname;//私有成员
};

6-2 多重继承派生类构造函数

C++-6-2

作者 范鹏程

单位 内蒙古师范大学

根据所给的基类Student和Teacher,定义Graduate类

类定义:

#include <iostream>
#include <string>
using namespace std;
class Teacher
{public:
Teacher(string nam,int a,string t)
{name=nam;
age=a;
title=t;}
void display()
{cout<<"name:"<<name<<endl;
cout<<"age"<<age<<endl;
cout<<"title:"<<title<<endl;
}
protected:
string name;
int age;
string title;
};

class Student
{public:
Student(string nam,char s,float sco)
{name1=nam;
sex=s;
score=sco;}
void display1()
{cout<<"name:"<<name1<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"score:"<<score<<endl;
}
protected:
string name1;
char sex;
float score;
};

/* 请在这里填写答案 */

裁判测试程序样例:

int main( )
{Graduate grad1("Wang-li",24,'f',"assistant",89.5,1234.5);
grad1.show( );
return 0;
}

输出样例:

name:Wang-li
age:24
sex:f
score:89.5
title:assistant
wages:1234.5

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Graduate:public Teacher,public Student
{
public:
Graduate(string name12,int age1,char sex2,string title1,float score2,float wages3)
:Teacher(name12,age1,title1),Student(name12,sex2,score2)
{wages=wages3;}
void show()
{
cout<<"name:"<<name1<<endl;
cout<<"age:"<<age<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"score:"<<score<<endl;
cout<<"title:"<<title<<endl;
cout<<"wages:"<<wages<<endl;
}
private:
float wages;
};

6-3 你好,继承和构造函数

C++-6-3

作者 向训文

单位 惠州学院

如下已经给出Person类的定义,请完善员工类Employee的定义。

  • Employee类继承自Person类
  • 新增了工资对应的数据成员
  • 新增了getSalary成员函数,用于获取该员工的工资。

裁判测试程序样例:

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

class Person {
public:
Person(string name, int age): m_name(name), m_age(age) {}
string getName() const { return m_name; }
int getAge() const { return m_age; }
protected:
string m_name; // 姓名
int m_age; // 年龄
};

class Employee: public Person { // 继承Person类
// 请将答案填写在这里

int main() {
string name; // 姓名
int age; // 年龄
float salary; // 工资
cin >> name >> age >> salary;
Person p(name, age);
cout << p.getName() << " " << p.getAge() << endl;
Employee e(name, age, salary);
cout << e.getName() << " " << e.getAge() << " " << e.getSalary() << endl;
return 0;
}

输入样例:

输入姓名、年龄、工资。例如:

tom 18 1000.3

输出样例:

在这里给出相应的输出。例如:

tom 18
tom 18 1000.3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

    public:
float getSalary()
{return salary;}
Employee(string n, int a,float s):Person(n,a)
{salary=s;}
private:
float salary;
};

十、2024.4.16——2024春面向对象程序设计作业05

C++-10

(1)单选题

C++-10.1

2-1(C)

假设已经定义好了一个类student,现在要定义类derived,它是从student私有派生的,定义类derived的正确写法是( )。

A.class derived:student private{…};

B.class derived:student public{…};

C.class derived:private student{…};

D.class derived:public student{…};

2-2(A)

下列关于类定义的说法中,正确的是

A.类定义中包括数据成员和函数成员的声明

B.类成员的缺省访问权限是保护的

C.数据成员必须被声明为私有的

D.成员函数只能在类体外进行定义

2-3(D)

基类中的私有成员,在公有派生类中的访问属性是( )。

A.公有

B.私有

C.保护

D.不可直接访问

2-4(B)

基类中的保护成员,在私有派生类中的访问属性是( )。

A.公有

B.私有

C.保护

D.不可直接访问

2-5(A)

对含有对象成员的派生类的构造函数和析构函数的描述中,以下错误的是( )。

A.创建派生类对象时,基类的构造函数最迟被执行

B.创建派生类对象时,内嵌对象成员的构造函数比派生类的构造函数更早执行

C.撤消派生类对象时,派生类的析构函数最先被执行

D.撤消派生类对象时,基类的构造函数最迟被执行

2-6(C)

在C++中,关于派生类访问基类成员的说法,以下哪项是正确的?

A.派生类可以直接访问基类的所有成员

B.派生类只能访问基类的公有(public)成员

C.派生类可以访问基类的公有(public)和保护(protected)成员,但不能访问私有(private)成员

D.派生类无法访问基类的任何成员

2-7(C)

在C++中,关于基类私有成员在派生类中的表现和可访问性,以下说法正确的是 __

A.派生类可以直接访问继承自基类的私有成员

B.派生类无法继承基类的私有成员

C.派生类可以继承基类的私有成员,但无法直接访问它们

D.派生类需要通过特定的访问修饰符才能继承基类的私有成员

2-8(A)

考虑以下C++代码:

class Base {  
private:
int privateVar;
protected:
int protectedVar;
public:
int publicVar;

Base() : privateVar(1), protectedVar(2), publicVar(3) {}
};
class Derived : public Base {
public:
void printVars() {
// 尝试访问基类的成员变量
// 以下哪些行会导致编译错误?
std::cout << privateVar << std::endl; // A
std::cout << protectedVar << std::endl; // B
std::cout << publicVar << std::endl; // C
}
};
int main() {
Derived d;
d.printVars();
return 0;
}

在上述代码中,关于printVars函数内尝试访问基类成员变量的行为,以下说法正确的是:

A.行A将导致编译错误,因为privateVar是私有的,派生类无法访问。

B.行B将导致编译错误,因为protectedVar是受保护的,派生类无法访问。

C.行C将导致编译错误,因为publicVar是公有的,但在派生类中无法直接访问。

D.所有行都不会导致编译错误,因为派生类可以访问基类的所有成员。

2-9(B)

下面关于继承和派生的构造函数和析构函数的程序,输出结果是

#include<iostream>
using namespace std;
class AA {
public:
AA() { cout << "A"; }
~AA() { cout << "a"; }
};
class BB: public AA {
AA aa;
public:
BB() { cout << "B"; }
~BB() { cout << "b"; }
};
int main() {
BB bb;
return 0;
}

A.AABaab

B.AABbaa

C.BAAaab

D.BAAbaa

2-10(B)

在创建派生类对象时,构造函数的执行顺序是( )。

A.对象成员构造函数、基类构造函数、派生类本身的构造函数

B.基类构造函数、对象成员构造函数、派生类本身的构造函数

C.基类构造函数、派生类本身的构造函数、对象成员构造函数

D.派生类本身的构造函数、基类构造函数、对象成员构造函数

(2)程序填空题

C++-10.2

5-1 包含子对象的派生类构造函数

C++-5-1

作者 范鹏程

单位 内蒙古师范大学

根据所定义的基类,定义派生类,请填空完成程序的功能

#include <iostream>
#include <string>
using namespace std;
class Student //声明基类
{public: //公用部分
Student(int n,string nam) //基类构造函数
{num=n;
name=nam;
}
void display() //输出基类数据成员
{cout<<"num:"<<num<<endl<<"name:"<<name<<endl;}
protected: //保护部分
int num;
string name;
};

class Student1: public Student //用public继承方式声明派生类student
{public:
Student1(int n1,string nam1,int n2,string nam2,int a,string ad):Student(n1,nam1),monitor(n2,nam2) //派生类构造函数
{age=a; //在此处只对派生类新增的数据成员初始化
addr=ad;
}
void show( )
{cout<<"This student is:"<<endl;
display(); //输出num和name
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl<<endl;
}

void show_monitor() //输出子对象的数据成员
{cout<<endl<<"Class monitor is:"<<endl;
monitor.display(); //调用基类成员函数
}
private: //派生类的私有数据
Student monitor; //定义子对象(班长)
int age;
string addr;
};

int main( )
{Student1 stud1(10010,"Wang-li",10001,"Li-sun",19,"115 Beijing Road,Shanghai");
stud1.show( ); //输出第一个学生的数据
stud1.show_monitor(); //输出子对象的数据
return 0;
}

程序输出如下

This student is:
num:10010
name:Wang-li
age: 19
address: 115 Beijing Road,Shanghai


Class monitor is:
num:10001
name:Li-sun

答案:

第一空:

Student1(int n1,string nam1,int n2,string nam2,int a,string ad):Student(n1,nam1),monitor(n2,nam2)

5-2 多层派生时的构造函数

C++-5-2

作者 范鹏程

单位 内蒙古师范大学

根据所定义的基类,完成派生类的定义。

#include <iostream>
#include<string>
using namespace std;
class Student
{public:
Student(int n, string nam )
{num=n;
name=nam;
}
void display()
{cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
}
protected:
int num;
string name;
};

class Student1: public Student
{public:
Student1(int n,string name,int a):Student(n,name)*/
{age=a; }
void show( )
{display();
cout<<"age: "<<age<<endl;
}
private:
int age;
};

class Student2:public Student1
{public:
Student2(int n,string name,int age,int s):Student1(n,name,age)
{score=s;}
void show_all()
{show();
cout<<"score:"<<score<<endl;
}
private:
int score;
};

int main( )
{Student2 stud(10010,"Li",17,89);
stud.show_all( );
return 0;
}

答案:

第一空:

Student1(int n,string name,int a):Student(n,name)

第二空:

Student2(int n,string name,int age,int s):Student1(n,name,age)

(3)函数题

C++-10.3

6-1 定义point类

6-1

作者 范鹏程

单位 内蒙古师范大学

根据给定的汽车类vehicle(包含的数据成员有车轮个数wheels和车重weight)声明,完成其中成员函数的定义,之后再定义其派生类并完成测试。

小车类car是它的派生类,其中包含载人数passenger_load。每个类都有相关数据的输出方法。

Vehicle类声明如下:

#include<iostream>
using namespace std;
class Vehicle
{
protected:
int wheels;
float weight;
public:
Vehicle(int wheels,float weight);
int get_wheels();
float get_weight();
float wheel_load();
void show();
};

/* 请在这里填写答案 */

裁判测试程序样例:

int main () 
{
Vehicle v(4,1000);
v.show();
Car car1(4,2000,5);
car1.show ();
return 0;
}

输出样例:

在这里给出相应的输出。例如:

Type:Vehicle
Wheel:4
Weight:1000kg
Type:Car
Type:Vehicle
Wheel:4
Weight:2000kg
Load:5 persons

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Car:public Vehicle
{
private:
int passenger_load;
public:
Car(int v_wheels,float c_weight,int c_passenger_load):Vehicle(v_wheels,c_weight)
{passenger_load=c_passenger_load;}
int get_passenger_load()
{return passenger_load;}
void show()
{
cout<<"Type:Car"<<endl;
cout<<"Type:Vehicle"<<endl;
cout<<"Wheel:"<<get_wheels()<<endl;
cout<<"Weight:"<<get_weight()<<"kg"<<endl;
cout<<"Load:"<<get_passenger_load()<<" persons"<<endl;
}
};
Vehicle::Vehicle(int v_wheels,float v_weight)
{
wheels=v_wheels;
weight=v_weight;
}
int Vehicle::get_wheels()
{return wheels;}
float Vehicle::get_weight()
{return weight;}
float Vehicle::wheel_load()
{return wheels;}
void Vehicle::show()
{
cout<<"Type:Vehicle"<<endl;
cout<<"Wheel:"<<get_wheels()<<endl;
cout<<"Weight:"<<get_weight()<<"kg"<<endl;
}

6-2 鸭子也是鸟

6-2

作者 fpc

单位 内蒙古师范大学

按要求完成下面的程序:

1、定义一个Bird类,包含一个void类型的无参的speak方法,输出“Jiu-Jiu-Jiu”。

2、定义一个Duck类,公有继承自Bird类,其成员包括:

(1)私有string类型的成员name;

(2)带参数的构造函数,用指定形参对私有数据成员进行初始化;

(3)公有的成员函数printName,无形参,void类型,功能是输出成员name的值,具体输出格式参见main函数和样例输出。

裁判测试程序样例:

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

/* 请在这里填写答案 */

int main()
{
Bird b;
b.speak();
Duck d("Donald"); //定义派生类对象
d.printName(); //派生类对象使用本类成员函数
d.speak(); //派生类对象使用基类成员函数
return 0;
}

输入样例:

无输入

输出样例:

Jiu-Jiu-Jiu
Dird Name:Donald
Jiu-Jiu-Jiu

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Bird
{
public:
void speak()
{cout<<"Jiu-Jiu-Jiu"<<endl;}
};
class Duck:public Bird
{
private:
string name;
public:
Duck(string b_name)
{name=b_name;}
string get_name()
{return name;}
void printName()
{cout<<"Dird Name:"<<get_name()<<endl;}
};

九、2024.4.11——2024春面向对象程序设计上机练习05

C++-9

(1)程序填空题

C++-9.1

5-1 自定义拷贝构造函数的使用练习2

C++-5-1

作者 王荣海

单位 泉州师范学院

本程序涉及自定义拷贝构造函数的使用,程序输出为:

30 40  
90 120

请把空白的代码补充完整。

#include<iostream>
using namespace std;
class point{
int x,y;
public:
point(int a,int b) { x=a;y=b; }
point(const point &p)
{ x=p.x*3;y=p.y*3; }
void print() { cout<<x<<" "<<y<<endl; }
};
int main() {
point p1(30,40);
point p2(p1);
p1.print();
p2.print();
return 0;
}

答案:

第一空:

x=a;y=b;

第二空:

x=p.x*3;y=p.y*3;

第二空:

point p1(30,40);

5-2 作用域运算符的使用

C++-5-2

作者 wrh

单位 泉州师范学院

以下是关于作用域运算符使用的程序,请完成程序填空。

输入:
100
输出结果:
102
#include <iostream>
using namespace std;
int i=99;
int main() {
int i;
cin>>i;
::i=102;
cout<<::i<<endl;
return 0;
}

答案:

第一空:

::i=102;

(2)函数题

C++-9.2

6-1 私有继承派生类使用基类的成员函数

C++-6-1

作者 李廷元

单位 中国民用航空飞行学院

按要求完成下面的程序:

1、定义一个Animal类,成员包括:

(1)整数类型的私有数据成员m_nWeightBase,表示Animal的体重;

(2)整数类型的保护数据成员m_nAgeBase,表示Animal的年龄;

(3)公有函数成员set_weight,用指定形参初始化数据成员m_nWeightBase;

(4)公有成员函数get_weight,返回数据成员m_nWeightBase的值;

(5)公有函数成员set_age,用指定形参初始化数据成员m_nAgeBase;

2、定义一个Cat类,私有继承自Animal类,其成员包括:

(1)string类型的私有数据成员m_strName;

(2)带参数的构造函数,用指定形参对私有数据成员进行初始化;
(3)公有的成员函数set_print_age,功能是首先调用基类的成员函数set_age设置数据成员m_nAgeBase的值为5,接着输出成员m_strName的值,然后输出“, age = ”,最后调用基类的成员函数get_age输出基类的数据成员m_nAgeBase的值。具体输出格式参见main函数和样例输出。

(4)公有的成员函数set_print_weight,功能是首先调用基类的成员函数set_weight设置数据成员m_nWeightBase的值为6,接着输出成员m_strName的值,然后输出“, weight = ”,最后调用基类的成员函数get_weight输出基类的数据成员m_nWeightBase的值。具体输出格式参见main函数和样例输出。

类和函数接口定义:

参见题目描述。

裁判测试程序样例:

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

/* 请在这里填写答案 */

int main()
{
Cat cat("Persian"); //定义派生类对象cat
cat.set_print_age();
cat.set_print_weight(); //派生类对象调用自己的公有函数
return 0;
}

输入样例:

本题无输入。

输出样例:

Persian, age = 5
Persian, weight = 6

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Animal
{
private:
int m_nWeightBase;
protected:
int m_nAgeBase;
public:
void set_weight(int weight)
{m_nWeightBase=weight;}
int get_weight()
{return m_nWeightBase;}
void set_age(int age)
{m_nAgeBase=age;}
};
class Cat:private Animal
{
private:
string m_strName;
public:
Cat(string c){m_strName=c;}
void set_print_age()
{
set_age(5);
cout<<m_strName<<", "<<"age = "<<m_nAgeBase<<endl;
}
void set_print_weight()
{
set_weight(6);
cout<<m_strName<<", "<<"weight = "<<get_weight()<<endl;
}
};

6-2 学生信息输入输出

C++-6-2

作者 范鹏程

单位 内蒙古师范大学

根据给出的基类,定义派生类,完成学生信息的输入输出(参见输入输出样例)

基类定义:

#include <iostream>
#include <string>
using namespace std;
class Student
{public:
void get_value()
{cin>>num>>name>>sex;}
void display( )
{cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;}
private :
int num;
string name;
char sex;
};

/*在这里添加派生类的定义*/

测试程序样例:

int main()
{Student1 stud1;
stud1.get_value();
stud1.get_value_1();
stud1.display();
stud1.display_1();
return 0;
}

输入样例:

1002 Lisi F
20 beijing

输出样例:

num: 1002
name: Lisi
sex: F
age: 20
address: beijing

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Student1:public Student
{
private:
int age;
string address;
public:

void get_value_1()
{
cin>>age>>address;
}
void display_1()
{
cout<<"age: "<<age<<endl;
cout<<"address: "<<address<<endl;
}
};

6-3 类的定义(学生类Student)

C++-6-3

作者 刘骥

单位 重庆大学

本题要求定义一个学生类Student,数据成员包含姓名name和年龄age,类的声明见给出的代码,请给出类的完整实现,并通过测试程序。

类的声明:

class Student{
private:
string name;
int age;
public:
Student(string name,int age);
string getName() const;
int getAge() const ;
void setName(string name);
void setAge(int age);
};

测试程序:

#include<iostream>
#include<string>
using namespace std;
class Student{
private:
string name;
int age;
public:
Student(string name,int age);
string getName() const;
int getAge() const ;
void setName(string name);
void setAge(int age);
};

/* 请在这里填写答案 */

int main(){
Student a("Zhang",20);
cout<<"name="<<a.getName()<<endl;
cout<<"age="<<a.getAge()<<endl;
a.setName("Li");
a.setAge(30);
cout<<"name="<<a.getName()<<endl;
cout<<"age="<<a.getAge()<<endl;
return 0;
}

测试程序的输入:


测试程序的输出:

name=Zhang
age=20
name=Li
age=30

提示

下列代码为类实现的骨架代码

Student::Student(string name,int age){
//代码
}
string Student::getName() const{
//代码
}
int Student::getAge() const{
//代码
}
void Student::setName(string name)
{
//代码
}
void Student::setAge(int age)
{
//代码
}

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Student::Student(string cname,int cage){name=cname;age=cage;}
string Student::getName() const{return name;}
int Student::getAge() const{return age;}
void Student::setName(string cname){name=cname;}
void Student::setAge(int cage){age=cage;}

八、2024.4.08——2024春面向对象程序设计上机练习04

C++-8

(1)程序填空题

C++-8.1

5-1 知识点3:friend修饰的成员变量与成员函数

C++-5-1

作者 郑远

单位 中国民用航空飞行学院

生活中你的家有客厅(Public),有你的卧室(Private);客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去。但是呢,你也可以允许你的好闺蜜好基友进去。

在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术;友元的目的就是让一个函数或者类 访问另一个类中私有成员

友元的关键字为 friend
友元的三种实现

  • 类做友元

  • 成员函数做友元

  • 全局函数做友元

  1. friend修饰别的类
  • 友元类可以声明在类中任意位置。friend class 类名

  • 声明友元类之后,友元类中的所有成员函数都是该类的友元函数,能够访问该类的所有成员。

  1. friend修饰成员函数
  • 友元成员函数声明语法:friend 函数返回值类型 类名::函数名();

  • 注意定义的先后,建议在前面进行声明,后面进行函数的同一定义,防止出现问题。

  1. friend修饰类外定义的函数
  • 将类外部的普通函数作为类的友元函数,在类中使用friend关键字声明该普通函数就可以实现,友元函数可以在类中任意位置声明。

  • 普通函数作为友元函数的声明形式如下所示: friend 函数返回值类型 友元函数名(形参列表)

#include<iostream>
using namespace std;
class Building;
class goodGay
{
public:
goodGay();
void visit();
private:
Building *building;
};
class goodGayGay
{
public:
goodGayGay();
void visit(); //只让visit函数作为Building的好朋友,可以发访问Building中私有内容
void visit2();
private:
Building *building;
};
class Building
{
//1.告诉编译器 goodGay类是Building类的好朋友,可以访问到Building类中私有内容
friend goodGay;
//2.告诉编译器 goodGayGay类中的visit成员函数 是Building好朋友,可以访问私有内容
friend void goodGayGay::visit();
//3.告诉编译器 printt全局函数 是 Building类的好朋友,可以访问类中的私有内容
friend void printt(Building * building);


public:
Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
//以下为具体定义函数
goodGay::goodGay()
{
building = new Building;
}
void goodGay::visit()
{
cout << "第一个好基友正在访问" << building->m_SittingRoom << endl;
cout << "第一个好基友正在访问" << building->m_BedRoom << endl;
}
goodGayGay::goodGayGay()
{
building = new Building;
}
void goodGayGay::visit()
{
cout << "第二个好基友正在访问" << building->m_SittingRoom << endl;
cout << "第二个好基友正在访问" << building->m_BedRoom << endl;
}
void goodGayGay::visit2()
{
cout << "第二个好基友正在第二次访问" << building->m_SittingRoom << endl;
//cout << "第二个好基友正在第二次访问" << building->m_BedRoom << endl;
}
void printt(Building * building)
{
cout << "第三个好基友正在访问: " << building->m_SittingRoom << endl;
cout << "第三个好基友正在访问: " << building->m_BedRoom << endl;
}
void test01()
{
goodGay gg;
gg.visit();
}
void test02()
{
goodGayGay gg;
gg.visit();
}
void test03()
{
Building b;
printt(&b);
}

int main(){
test01();//friend修饰别的类
test02();//friend修饰成员函数
test03();//friend修饰类外定义的函数
return 0;
}

答案:

第一空:

friend goodGay;

第二空:

friend void goodGayGay::visit();

第三空:

friend void printt(Building * building);

5-2 知识点1:const修饰的成员变量与成员函数

C++-5-2

作者 郑远

单位 中国民用航空飞行学院

常成员变量:

  • 对于常成员变量,仅仅可以读取第一次初始化的数据,之后是不能修改的。
  • 常成员变量通常使用有参数构造函数进行初始化.
  • 语法 const 变量类型 变量名

常函数:

  • 成员函数后加const后我们称为这个函数为常函数
  • 常函数内不可以修改成员属性
  • 类中定义的成员函数若与常成员函数名相同则构成重载,常成员函数只能由const修饰的对象进行访问。
  • 语法:返回值类型 函数名() const {}

常对象:

  • 声明对象前加const称该对象为常对象
  • 常对象只能调用常函数
  • 语法:const 类名 对象名(构造函数参数)

语法:

#include<iostream>
using namespace std;
class Person {
public:
Person():m_A(1) {//const 修饰的成员变量,只有初始化时可以对其进行赋值,这里需要用初始化列表对m_A赋初值为1
//const 修饰的成员变量需要用初始化参数表进行赋值,不能在函数体中进行赋值,这句话会报错
//m_A = 0;
m_B = 0;

}
//定义常成员函数ShowPerson,无返回值,无输入参数
void ShowPerson() const{
//const修饰成员函数,内部不能修改类成员,以下语句会报错
//this->m_B = 100;
//但是可以调用
cout<<this->m_B<<endl;
cout<<"重载2"<<endl;
}
//定义非常成员函数ShowPerson,与上面函数构成重载,无返回值,无输入参数
void ShowPerson() {

cout<<"重载1"<<endl;
}
void MyFunc(){
//const修饰的成员变量,除了初始化以外,在哪都不允许被修改,以下语句会报错
//mA = 10000;
//但是可以调用
cout<<this->m_A<<endl;
}
public:
const int m_A;
int m_B;
};
int main(){
const Person person1;//常量对象
Person person2;//正常对象

//正常对象调用showperson,调用的是未经const修饰的重载函数showperson
person2.ShowPerson();
person2.MyFunc();

//常对象调用showperson,调用的是经过const修饰的重载函数showperson
person1.ShowPerson();
//常对象不能调用普通成员函数,以下语句会报错
//person1.MyFunc();

return 0;
}
//程序最后输出为:
//第一行:重载1
//第二行:1
//第三行:0
//第四行:重载2

答案:

第一空:

:m_A(1)

第二空:

void ShowPerson() const

第三空:

void ShowPerson()

第四空:

重载1

第五空:

1

第六空:

0

第七空:

重载2

(2)函数题

C++-8.2

6-1 使用类及友元实现输入姓名和年龄,按格式输出所输入的姓名与年龄

C++-6-1

作者 王荣海

单位 泉州师范学院

本题实现输入姓名和年龄,按格式输出所输入的姓名与年龄,使用类及友元实现。要求创建一个类girl,类girl有两个私有数据成员name(string类型)和age(int类型),disp函数是类girl的友元函数,用来输出 girl对象成员的name和age,disp函数和main函数已经实现,请编写girl类的全部代码。

girl类定义框架:

class girl {
public:
// 这里编写构造函数实现及友元函数声明代码
private:
//这里编写私有成员声明代码
};

测试程序样例:

#include <iostream>
#include <string>
using namespace std;
/*girl类代码将被插入在这个位置*/
void disp(girl& x) {
cout<<"name:"<<x.name;
cout<<",age:"<< x.age<<"\n";
}
int main() {
string m_name;
int m_age;
cin>>m_name>>m_age;
girl girl1(m_name,m_age);
disp(girl1);
return 0;
}

输入样例:

Zhangsan 18

输出样例:

name:Zhangsan,age:18

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class girl {
public:
friend void disp(girl& x);
girl(string m_name,int m_age)
{ name=m_name; age=m_age;}
private:
string name;
int age;
};

6-2 给你介绍个对象,想要不?

C++-6-2

作者 向训文

单位 惠州学院

编写函数display,传入一个Person类的对象

裁判测试程序样例:

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

class Person {
public:
Person(string name): m_name(name) {
cout << "create Person: " << m_name << endl;
}
Person(const Person &p) {
cout << "copy Person: " << m_name << endl;
m_name = p.m_name;
}
~Person() {
cout << "destroy Person: " << m_name << endl;
}
string getName() const { return m_name; }
private:
string m_name;
};

// 请把答案写在这里

int main()
{
string name;
cin >> name;
Person p(name);
display(p);
return 0;
}

输入样例:

在这里给出一组输入。例如:

tom

输出样例:

在这里给出相应的输出。例如:

create Person: tom
tom
destroy Person: tom

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void display(const Person &p)
{
cout<<p.getName()<<endl;
}

6-3 判断一个点是否在一个圆的内部

C++-6-3

作者 杨军

单位 四川师范大学

创建一个表示点的类Point,运用组合的方式创建圆形类。
圆形有个成员函数isPointIn用于判断一个点是否在该圆形的内部。
完成对应类代码,使得主函数可以正确运行。
注意类的数值型数据成员类型为浮点型。

裁判测试程序样例:

/* 请在这里填写答案 */
int main(int argc, char const *argv[])
{
double x,y;
double r;
cin>>x>>y>>r;
Point p(x,y);
Circle c(p,r);
cin>>x>>y;
Point p1(x,y);
bool b = c.isPointIn(p1);
cout<<b<<endl;
}

输入样例:

在这里给出一组输入。例如:

1 1 1.5 2 2

输出样例:

在这里给出相应的输出。例如:

1

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include<iostream>
using namespace std;
#define Yes 1;
#define No 0;
class Point
{
private:
double m_x;
double m_y;
public:
Point(double x, double y)
{
m_x = x; m_y = y;
}
double getx() { return m_x; }
double gety() { return m_y; }

};
class Circle
{
private:
double c_x;
double c_y;
double c_r;
public:
Circle(Point& p, double r)
{
c_r = r; c_x = p.getx(); c_y = p.gety();
}
bool isPointIn(Point& p)
{
int l,x=p.getx(), y = p.gety();
l = (x - c_x) * (x - c_x) + (y - c_y) * (y - c_y);
if (l < c_r * c_r)
return Yes;
return No;
}
};

七、2024.4.09——2024春面向对象程序设计作业04

C++-7

(1)判断题

C++-7.1

1-1(T)

每个类都必须有一个拷贝构造函数。

1-2(F)

构造函数的名字可以与类名相同,也可以与类名不同。

1-3(F)

在C++局部变量的作用域内,不可用::对被屏蔽的同名全局变量进行访问。

1-4(T)

不论是数据成员,还是成员函数,只要是公有的,在类的外部可以通过类的对象进行访问。

1-5(F)

公有成员函数在类的外部可以通过类的对象进行访问,公有数据成员在类的外部不可以通过类的对象进行访问。

1-6(F)

在C++中构造函数和析构函数都不可以重载。

1-7(F)

假设Complex是复数类,执行Complex com[10];

com的元素个数是9个。

1-8(T)

当用指向对象的指针来访问对象成员时,只能使用“->”操作符,不能使用点运算符“.”。

1-9(T)

如果在一个类中说明了常数据成员,那么构造函数就只能通过成员初始化列表对该数据成员进行初始化。

1-10(T)

面向对象程序一般由类的定义和类的使用两部分组成

(2)单选题

C++-7.2

2-1(D)

下列语句中错误的是( )。

A.int *p = new int(20);

B.int *p = new int[20];

C.int *p = new int;

D.int *p = new int[40] (10);

2-2(B)

在( )情况下适宜采用内联函数。

A.函数代码多,频繁调用

B.函数代码少,频繁调用

C.函数体含有递归语句

D.函数体含有循环语句

2-3(B)

在C++中,关于下列设置默认参数值的描述中,( )是正确的。

A.不允许设置默认参数值

B.在指定了默认值的参数右边,不能出现没有指定默认值的参数

C.只能在函数的定义性声明中指定参数的默认值

D.设置默认参数值时,必须全部都设置

2-4(B)

在下面有关对构造函数的描述中,正确的是( )。

A.构造函数可以带有返回值

B.构造函数的名字与类名完全相同

C.构造函数必须带有参数

D.构造函数必须定义,不能默认

2-5(C)

关于new运算符的下列描述中,( )是错误的。

A.它可以用来动态创建对象和对象数组

B.使用它创建的对象或对象数组可以使用运算符delete删除

C.使用它创建对象时要调用构造函数

D.使用它创建对象数组时必须指定初始值

2-6(C)

在下面有关析构函数特征的描述中,正确的是( )。

A.一个类中可以定义多个析构函数

B.析构函数名与类名完全相同

C.析构函数不能指定返回类型

D.析构函数可以有一个或多个参数

2-7(B)

在下面有关静态成员函数的描述中,正确的是( )

A.在静态成员函数中可以使用this指针

B.在创建对象前,就可以为静态数据成员赋值

C.静态成员函数在类外定义时,要用static前缀

D.静态成员函数只有在类外定义

2-8(C)

下列关于构造函数的描述中,错误的是( )。

A.构造函数可以设置默认参数

B.构造函数可以是内联函数

C.构造函数不可重载

D.构造函数在创建类对象时自动执行

2-9(D)

下面的类型声明中正确的是( )。

A.int &b[4];

B.int & *q;

C.int && p;

D.int j, *p=&j;

2-10(B)

构造函数是在( )时被执行的。

A.程序编译

B.创建对象

C.创建类

D.程序装入内存

(3)程序填空题

C++-7.3

5-1 用成员初始化列表对数据成员进行初始化练习2

C++-5-1

作者 王荣海

单位 泉州师范学院

以下程序实现用成员初始化列表对引用类型的数据成员和const修饰的数据成员进行初始化,以下程序输出结果为:
x=50 refx=50 pi=3.14
请把代码中空缺的部分补充完整。

#include<iostream> 
using namespace std;
class A{
public:
A(int x1):x(x1),refx(x),pi(3.14){ }
void print() {
cout<<"x="<<x<<" "<<"refx="<<refx<<" "<<"pi="<<pi<<endl;
}
private:
int x;
int& refx;
const double pi;
};
int main() {
A b(50);
b.print();
return 0;
}

答案:

第一空:

m=n;

第二空:

A b(50);

5-2 构造函数的使用

C++-5-2

作者 王荣海

单位 泉州师范学院

本程序实现输入两个数,输出所输入的两个数,例如:
输入
10 20
输出
10 20
请将空缺的代码补全。

#include <iostream>
using namespace std;
class Location{
private:
int m,n;
public:
Location (int x,int y)
{
m=x;
n=y;
}
int Getm()
{
return m;
}
int Getn()
{
return n;
}
};
int main() {
int a,b;
cin>>a>>b;
Location test(a,b);
cout<<test.Getm()<<" "<<test.Getn()<<endl;
return 0;
}

答案:

第一空:

int m,n;

第二空:

int x,int y

第三空:

return m;

第四空:

return n;

5-3 对象数组

C++-5-3

作者 范鹏程

单位 内蒙古师范大学

将空白的地方填写完整,使程序完成指定的功能。

#include <iostream>
using namespace std;
class Student
{public:
Student(int x, float y){num=x,score=y;}; //利用参数初始化表进行数据初始化
void display();
private:
int num;
float score;
};

void Student::display()
{cout<<num<<" "<<score<<endl;}

int main()
{
Student stud[5]={
Student(101,78.5),Student(102,85.5),Student(103,98.5),
Student(104,100.0),Student(105,95.5)}; //定义对象数组
Student *p=stud; //定义对象指针指向对象数组
for(int i=0;i<3;i++,p+=2)//显示第1、3、5名学生信息
p->display();
return 0;
}
}

答案:

第一空:

Student(int x, float y){num=x,score=y;};

第二空:

Student *p=stud;

第三空:

int i=0;i<3;i++,p+=2

5-4 知识点2:static修饰的成员变量与成员函数

C++-5-4

作者 郑远

单位 中国民用航空飞行学院

静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员
静态成员分为:

  • 静态成员变量

    *  所有对象共享同一份数据    *  在编译阶段分配内存    *  静态成员变量定义语法 `static 变量类型 变量名`      *  类内声明,类外初始化,初始化语法为:`变量类型 类名::变量名=初始化数(整体位于类定义的外面)`      *  可以通过对象或类进行调用:`对象.静态成员变量名`或`类名::静态成员变量名`
  • 静态成员函数

    *  所有对象共享同一个函数    *  静态成员函数只能访问静态成员变量    *  静态成员函数定义语法:`static 函数名(){}`      *  可以通过对象或类进行调用:`对象.静态函数名()`或`类名::静态函数名()`
#include<iostream>
using namespace std;
class Person
{

public:
static int m_A; //静态成员变量
static void func() //静态成员函数func,没有输入
{
cout << "func调用" << endl;
m_A = 100;
//m_B = 100; //静态成员函数不可以访问非静态成员变量,这句话会报错
}
private:
static void func2()//静态成员函数也是有访问权限的
{
cout << "func2调用" << endl;
}
static int m_B; //静态成员变量也是有访问权限的
};
//静态成员变量初始化,私有对象可以在外面初始化但访问不了
int Person::m_A = 10;//初始化m_A
int Person::m_B = 10;
int main() {
//静态成员变量两种访问方式
//1、通过对象
Person p1;
p1.m_A = 100;//通过对象调用m_A
cout << "p1.m_A = " << p1.m_A << endl;

Person p2;
p2.m_A = 200;
cout << "p1.m_A = " << p1.m_A << endl; //共享同一份数据
cout << "p2.m_A = " << p2.m_A << endl;

//2、通过类名
cout << "m_A = " << Person::m_A << endl;//通过类名调用m_A
//cout << "m_B = " << Person::m_B << endl; //私有权限访问不到


//静态成员函数两种访问方式
//1、通过对象
Person p3;
p3.func(); //通过对象调用成员函数
//2、通过类名
Person::func(); //通过类调用成员函数
//Person::func2(); //私有权限访问不到


return 0;
}

答案:

第一空:

static int 

第二空:


static void func()

第三空:

int Person::m_A

第四空:

p1.m_A 

第五空:

Person::m_A

第六空:

p3.func();

第七空:

Person::func();

5-5 你好,构造函数的初始化列表

C++-5-5

作者 向训文

单位 惠州学院

在构造函数中,使用初始化列表对数据成员进行初始化:
样例程序:

#include<iostream> 
using namespace std;
class Point {
public:
// 构造函数,使用初始化列表对数据成员进行初始化
Point(int x, int y):m_x(x),m_y(y) {}
int getX() { return m_x; }
int getY() { return m_y; }
private:
int m_x, m_y;
};
int main() {
int x, y;
cin >> x >> y; // 输入点的x,y坐标
Point p(x, y); // 创建点对象
cout << p.getX() << " " << p.getY() << endl; // 输出点的坐标
return 0;
}

答案:

:m_x(x),m_y(y)

(4)函数题

C++-7.4

6-1 定义example类

6-1

作者 王荣海

单位 泉州师范学院

请编写example类的全部代码,实现程序运行后输出结果为:

1 2 3 4

example类定义框架:

class example { 
    private: // 这里编写数据成员声明代码
    public: //这里编写构造函数及相关成员函数实现代码
};

测试程序样例:

#include <iostream>
#include <string>
using namespace std;
/*example类代码将被插入在这个位置*/
int main() {
example ex[4]={1, 2, 3, 4};
for (int i=0;i<4;i++)
cout<<ex[i].get_x()<<' ';
return 0;
}

输入样例:

无

输出样例:

1 2 3 4 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class example {
private:
int x;
public:
example(int m){x=m;};
int get_x(){return x;}
};

6-2 你好,拷贝构造函数

6-2

作者 向训文

单位 惠州学院

定义一个类Point:

  • 构造函数传入x和y的坐标值(整数),如果不传,默认都为0
  • 编写复制构造函数
  • display函数用于输出这个点的x和y坐标,以空格分隔

裁判测试程序样例:

#include <iostream>
using namespace std;

// 答案写在这里

int main()
{
int x, y;
cin >> x >> y;
Point p1(x, y);
Point p2;
Point p3(p1);
p1.display();
p2.display();
p3.display();
return 0;
}

输入样例:

在这里给出一组输入。例如:

3 4

输出样例:

在这里给出相应的输出。例如:

3 4
0 0
3 4

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Point
{
private:
int m_x,m_y;
public:
Point(int x=0,int y=0){m_x=x;m_y=y;}
void display(){cout<<m_x<<" "<<m_y<<endl;}
};

6-3 你好,类外定义成员函数

6-1

作者 向训文

单位 惠州学院

完善类Point中4个成员函数的定义:

  • setPoint: 设置点的x,y坐标
  • getX: 获取x坐标
  • getY: 获取y坐标
  • print: 打印点的信息

裁判测试程序样例:

#include<iostream> 
using namespace std;

class Point {
public:
void setPoint(int x, int y);
int getX();
int getY();
void print();
private:
int m_x, m_y;
};

// 请将答案填写在这里

int main() {
int x, y;
cin >> x >> y;
Point p;
p.setPoint(x, y); // 设置点的坐标
cout << "x: " << p.getX() << endl; // 输出x坐标
cout << "y: " << p.getY() << endl; // 输出y坐标
p.print(); // 打印点的信息
return 0;
}

输入样例:

输入点的x,y坐标。例如:

21 2

输出样例:

输出点的x,y坐标,以及点的信息。例如:

x: 21
y: 2
(21, 2)

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void Point::setPoint(int x,int y){m_x=x;m_y=y;}
int Point::getX(){return m_x;}
int Point::getY(){return m_y;}
void Point::print()
{cout<<"("<<m_x<<", "<<m_y<<")";}

6-4 你好,对象的定义和使用

6-4

作者 向训文

单位 惠州学院

如下代码中要求,使用不同方式创建Person类的对象,并使用它们:

裁判测试程序样例:

#include<iostream> 
using namespace std;

// 描述人的类
class Person {
public:
// 设置某个人的信息
void setInfo(int age, int height) {
m_age = age;
m_height = height;
}
// 获取这个人的年龄
int getAge() { return m_age; }
// 获取这个人的身高
int getHeight() { return m_height; }
// 打印这个人的信息
void print() {
cout << "age: " << m_age << ", height: " << m_height << endl;
}
private:
int m_age;
int m_height;
};

int main() {
int age;
double height;
cin >> age >> height; // 输入年龄和身高
// 请将答案填写在这里
// TODO 创建Person类的对象p1,调用setInfo设置年龄和身高,并调用print打印这个人的信息
// TODO 动态创建Person类的对象p2,调用setInfo设置年龄和身高,并调用print打印这个人的信息
// TODO 创建数组p3(普通数组,不是动态创建),大小为10,每个元素为Person类的对象,
// 调用setInfo设置下标为0的人的年龄和身高,并调用print打印这个人的信息
return 0;
}

输入样例:

输入某个人的年龄和身高。例如:

19 180

输出样例:

在这里给出相应的输出。例如:

age: 19, height: 180
age: 19, height: 180
age: 19, height: 180

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Person p1;
p1.setInfo(age,height);
p1.print();

Person p2;
p2.setInfo(age,height);
p2.print();

Person p3[10];
p3[0].setInfo(age,height);
p3[0].print();

6-5 客户机类

6-5

作者 杨军

单位 四川师范大学

实现客户机(Client)类。定义字符型静态数据成员ServerName,保存其服务器名称;整型静态数据成员ClientNum,记录已定义的客户机数量;定义静态函数ChangeServerName()改变服务器名称。完成程序,使得提供的测试程序可以运行并得到要求的结果。

函数接口定义:
根据要求实现类代码

裁判测试程序样例:
/在这里完成类代码/
在这里给出函数被调用进行测试的例子。例如:
int main(){
Client::show();
Client c1;
Client::show();
Client::changeServerName(‘B’);
Client::show();
}

输入样例:

在这里给出一组输入。例如:

无

输出样例:

在这里给出相应的输出。例如:

server name:A
num of clients:0
server name:A
num of clients:1
server name:B
num of clients:1

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include <iostream>
using namespace std;
class Client
{
private:
static char ServerName;
static int ClientNum;
public:
Client(){ClientNum++;}
static void show()
{cout<<"server name:"<<ServerName<<"\n"<<"num of clients:"<<ClientNum<<endl;}
static void changeServerName(char x){ServerName=x;}
};
char Client::ServerName='A';
int Client::ClientNum=0;

(5)编程题

C++-7.5

7-1 类的定义和使用

7-1

作者 wangxiu

单位 福州大学

请定义一个Point类,有两个数据成员:x和y, 分别代表x坐标和y坐标,并有若干构造函数和一个移动的成员函数,可输出移动后新的坐标值。

输入:

第一行的两个数 分别表示 点的x坐标和y坐标。 第二行的两个数 分别表示 x和y方向移动的距离。

输出:

移动后的点的x坐标和y坐标。

输入样例:

1  5
2 5

输出样例:

3 10

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include <iostream>
using namespace std;
class zb
{
public:
zb(int x, int y) {m_x=x,m_y=y;};
void plus(int m, int n);
int getx();
int gety();
private:
int m_x, m_y;
};

void zb::plus(int m,int n)
{
m_x = m_x + m; m_y = m_y + n;
}

int zb::getx()
{
return m_x;
}

int zb::gety()
{
return m_y;
}

int main()
{
int x, y, m, n;
cin >> x >> y;
zb zb1(x, y);
cin >> m >> n;
zb1.plus(m, n);
cout << zb1.getx() << " " << zb1.gety();
return 0;
}

7-2 计算若干个学生的总成绩及平均成绩

7-2

作者 kww

单位 西安邮电大学

这是一个编程题模板。

定义一个类Student,记录学生C++课程的成绩。要求使用静态数据成员或静态成员函数计算若干个学生C++课程的总成绩和平均成绩。

输入格式:

输入n个不超过100的正整数,作为C++成绩。

输出格式:

在第一行中输出成绩的和,第二行输出平均成绩。

输入样例:

在这里给出一组输入。例如:

3
30 40 50

输出样例:

在这里给出相应的输出。例如:

120
40

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include<iostream>
using namespace std;
class Student
{
private:
static int score;
static int num;
public:
static void cj(int x){score=score+x;num++;}
static int getcj(){return score;}
static int pj(){return score/num;}
};
int Student::score=0;
int Student::num=0;
int main()
{
Student st1;
int x,n=0;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x;
st1.cj(x);
}
cout<<st1.getcj()<<"\n"<<st1.pj();
}

六、2024.3.31——2024春面向对象程序设计上机练习03

C++-6

(1)程序填空题

C++-6.1

5-1 用成员初始化列表对数据成员进行初始化练习2

C++-5-1

作者 王荣海

单位 泉州师范学院

以下程序实现用成员初始化列表对引用类型的数据成员和const修饰的数据成员进行初始化,以下程序输出结果为:
x=50 refx=50 pi=3.14
请把代码中空缺的部分补充完整。

#include<iostream> 
using namespace std;
class A{
public:
A(int x1):x(x1),refx(x),pi(3.14){ }
void print() {
cout<<"x="<<x<<" "<<"refx="<<refx<<" "<<"pi="<<pi<<endl;
}
private:
int x;
int& refx;
const double pi;
};
int main() {
A b(50);
b.print();
return 0;
}

答案:

第一空:

x(x1),refx(x),pi(3.14)

第二空:

A b(50);

5-2 引用作为函数参数

C++-5-2

作者 wrh

单位 泉州师范学院

以下是关于引用作为函数参数的应用的程序,请完成程序填空。

输入:
6 8
输出结果:
6 6

#include
using namespace std;
void f(int m,int &n){
int temp;
temp=m;
m=n;
n=temp;

}
int main() {
int a,b;
cin>>a>>b;

    f(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}

答案:

第一空:

int &n

第二空:

A b(50);

第三空:

f(a,b)

(2)函数题

C++-6.2

6-1 你好,类外定义成员函数

C++-6-1

作者 向训文

单位 惠州学院

完善类Point中4个成员函数的定义:

  • setPoint: 设置点的x,y坐标
  • getX: 获取x坐标
  • getY: 获取y坐标
  • print: 打印点的信息

裁判测试程序样例:

#include<iostream> 
using namespace std;

class Point {
public:
void setPoint(int x, int y);
int getX();
int getY();
void print();
private:
int m_x, m_y;
};

// 请将答案填写在这里

int main() {
int x, y;
cin >> x >> y;
Point p;
p.setPoint(x, y); // 设置点的坐标
cout << "x: " << p.getX() << endl; // 输出x坐标
cout << "y: " << p.getY() << endl; // 输出y坐标
p.print(); // 打印点的信息
return 0;
}

输入样例:

输入点的x,y坐标。例如:

21 2

输出样例:

输出点的x,y坐标,以及点的信息。例如:

x: 21
y: 2
(21, 2)

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

void Point::setPoint(int x, int y)
{
m_x=x;
m_y=y;
}
int Point::getX()
{
return m_x;
}
int Point::getY()
{
return m_y;
}
void Point::print()
{
cout<<"("<<m_x<<", "<<m_y<<")";
}

6-2 你好,string(基础)

C++-6-2

作者 向训文

单位 惠州学院

你会使用string吗,完善程序,使程序正确运行:

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
cin >> str1 >> str2; // 输入两个字符串
// 将答案填写在这里
return 0;
}

输入样例:

输入两个字符串。例如:

ddd abc

输出样例:

  1. **按格式输出str1和str2连接之后的结果(不修改str1和str2本身)

  2. 按格式输出str1和"abc"连接之后的结果(不修改str1)

  3. 如果str2的内容为"abc",按格式输出yes,否则输出no

  4. 将str1和str2连接,并赋值给str1,按格式输出新的str1的值

  5. 输出新的str1的长度

  6. 输出新的str1中第3、4字符

    str1 + str2: dddabc
    str1 + abc: dddabc
    str2 == abc: yes
    new str1: dddabc
    length: 6
    substr: ab

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

cout<<"str1 + str2: "<<str1+str2<<endl;

cout<<"str1 + abc: "<<str1+"abc"<<endl;

if(str2=="abc")
{cout<<"str2 == abc: yes"<<endl;}
else
{cout<<"str2 == abc: no"<<endl;}

str1=str1+str2;
cout<<"new str1: "<<str1<<endl;

cout<<"length: "<<size(str1)<<endl;

cout<<"substr: "<<str1[3]<<str1[4];

6-3 对象数组初始化

C++-6-3

作者 范鹏程

单位 内蒙古师范大学

根据类定义,进行对象数组的定义,按照输出样例输出相应的数据。

类定义:

#include<iostream>
using namespace std;
class A{
int data;
public:
A(int k=0){
data=k;
}
void show(){
cout<<"data="<<data<<endl;
}
};

编写main函数,定义三个对象数组,完成指定的输出

/* 请在这里填写答案 */

输入样例:

无

输出样例:

在这里给出相应的输出。例如:

data=0
data=0
data=0

data=1
data=0
data=0

data=1
data=2
data=3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int main()
{
A a[3];
A b[3]={1};
A c[3]={1,2,3};


for(int i=0;i<3;i++)
a[i].show();
cout<<endl;
for(int i=0;i<3;i++)
b[i].show();
cout<<endl;
for(int i=0;i<3;i++)
c[i].show();

return 0;
}

6-4 Tree类的构造函数和成员函数

C++-6-4

作者 李廷元

单位 中国民用航空飞行学院

定义一个Tree(树)类,有成员ages(树龄),不带参数的构造函数对ages初始化为1,成员函数grow(int years)对ages加上years,age()显示tree对象的ages的值。

Tree类声明如下:

class Tree {
public:
Tree();//构造函数
void grow(int years);//对数龄ages加上years
void age();//显示数龄ages的值
private:
int ages;//树龄
};

请实现Tree类的构造函数和成员函数。

裁判测试程序样例:

#include <iostream>
using namespace std;

class Tree {
public:
Tree();//构造函数
void grow(int years);//对数龄ages加上years
void age();//显示数龄ages的值
private:
int ages;//树龄
};

int main()
{
Tree tree;
int years;
cin >> years;
tree.grow(years);
tree.age();

return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

30

输出样例:

31

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

Tree::Tree()
{ages=1;}
void Tree::grow(int years)
{ages=ages+years;}
void Tree::age()
{cout<<ages;}

6-5 类的声明和成员函数的实现—this指针

C++-6-5

作者 李廷元

单位 中国民用航空飞行学院

本题要求声明和实现一个Car类,包括实现其成员函数。

要求如下:

类和函数接口定义:

1. 声明一个Car类;
2. 三个public成员函数:
(1) disp_welcomemsg(),无返回类型;
(2) get_wheels(),返回一个Car类的数据成员m_nWheels的值;
(3) set_wheels(int),用指定的形参初始化数据成员m_nWheels的值;
3. 一个私有数据成员m_nWheels,整数类型,代表汽车的车轮数量。

其中,成员函数disp_welcomemsg()显示一条欢迎信息“Welcome to the car world!”。
成员函数get_wheels()返回Car类的私有数据成员m_nWheels。
成员函数set_wheels(int)用指定的形参初始化数据成员m_nWheels。

裁判测试程序样例:

#include <iostream>
using namespace std;

/* 请在这里填写答案 */

int main()
{
int n;
cin >> n;
Car myfstcar, myseccar; //定义类对象
myfstcar.disp_welcomemsg();//访问成员函数,显示欢迎信息
myfstcar.set_wheels(n); //访问成员函数,设置车轮数量
myseccar.set_wheels(n+4); //访问成员函数,设置车轮数量
//访问成员函数,显示车轮数量
cout << "my first car wheels num = " << myfstcar.get_wheels() << endl;
cout << "my second car wheels num = " << myseccar.get_wheels() << endl;

return 0;
}

输入样例:

4

输出样例:

Welcome to the car world!
my first car wheels num = 4
my second car wheels num = 8

输入样例:
30

输出样例:
31

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

#include <iostream>
using namespace std;

class Car
{
public:
void disp_welcomemsg();
int get_wheels();
void set_wheels(int x);
private:
int m_nWheels;
};
void Car::disp_welcomemsg()
{cout<<"Welcome to the car world!"<<endl;}
int Car::get_wheels()
{return m_nWheels;}
void Car::set_wheels(int x)
{m_nWheels=x;}

6-6 求Box的体积(类的定义与使用)

C++-6-6

作者 范鹏程

单位 内蒙古师范大学

本题要求实现一个类定义,可完成长方柱体积的计算与输出。

类定义:

类的名称为Box,完成类体的声明与实现

裁判测试程序样例:

在这里给出根据类进行对象定义与使用的主函数的示例:
int main()
{
Box box2;
box2.get_value();
box2.display();
return 0;
}

/* 请在这里填写答案 */

输入样例:

在这里给出一组输入。例如:

2 3 5

输出样例:

在这里给出相应的输出。例如:

30

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Box{
private:
float m_a,m_b,m_c;
public:
void get_value();
void display();
};
void Box::get_value()
{ cin>>m_a>>m_b>>m_c;}
void Box::display()
{cout<<m_a*m_b*m_c;}

五、2024.3.21——2024春面向对象程序设计上机练习02

C++-5

(1)程序填空题

C++-5.1

5-1 用成员初始化列表对数据成员进行初始化练习2

C++-5-1

作者 王荣海

单位 泉州师范学院

以下程序实现用成员初始化列表对引用类型的数据成员和const修饰的数据成员进行初始化,以下程序输出结果为:
x=50 refx=50 pi=3.14
请把代码中空缺的部分补充完整。

#include<iostream> 
using namespace std;
class A{
public:
A:(int x(x1),refx(x),pi(3.14) x1){ }
void print() {
cout<<"x="<<x<<" "<<"refx="<<refx<<" "<<"pi="<<pi<<endl;
}
private:
int x;
int& refx;
const double pi;
};
int main() {
A b(50);
b.print();
return 0;
}

答案:

第一空:

x(x1),refx(x),pi(3.14)

第二空:

A b(50);

5-2 构造函数的使用

C++-5-2

作者 王荣海

单位 泉州师范学院

本程序实现输入两个数,输出所输入的两个数,例如:
输入
10 20
输出
10 20
请将空缺的代码补全。

#include <iostream>
using namespace std;
class Location{
private:
int m,n;
public:
Location (int x,int y)
{
m=x;
n=y;
}
int Getm()
{
return m;
}
int Getn()
{
return n;
}
};
int main() {
int a,b;
cin>>a>>b;
Location test(a,b);
cout<<test.Getm()<<" "<<test.Getn()<<endl;
return 0;
}

答案:

第一空:

int m,n;

第二空:

int x,int y

第三空:

return m;

第四空:

return n;

5-3 引用作为函数参数的应用

C++-5-3

作者 wrh

单位 泉州师范学院

以下是关于引用作为函数参数的应用的程序,请完成程序填空。

输入:
5 8
输出结果:
5 5
#include <iostream>
using namespace std;
void f(int m,int &n){
int temp;
temp=m;
m=n;
n=temp;
}
int main() {
int a,b;
cin>>a>>b;
f(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}

答案:

第一空:

int m,int &n

第二空:

int a,b;

第三空:

f(a,b);

(2)函数题

C++-5.2

6-1定义point类

C++-6-1

作者 王荣海

单位 泉州师范学院

请编写point类的全部代码,实现程序运行后输出结果为:

op1 i=10 op1 j=20

point类定义框架:

class point {
private:
// 这里编写数据成员声明代码
public:
//这里编写相关成员函数实现代码
};

测试程序样例:

#include <iostream>
#include <string>
using namespace std;
/*point类代码将被插入在这个位置*/
int main() {
point op1;
int i,j;
op1.setpoint(10,20);
i=op1.getx();
j=op1.gety();
cout<<"op1 i="<<i<<" op1 j="<<j<<endl;
return 0;
}

输入样例:

无

输出样例:

op1 i=10 op1 j=20

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class point {
private:
int x,y;
public:
void setpoint(int a,int b)
{
x=a;
y=b;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
};

6-2 你好,构造函数

C++-6-2

作者 向训文

单位 惠州学院

编写Point类,使得下列程序正确运行:

裁判测试程序样例:

#include<iostream> 
using namespace std;

// 请将答案填写在这里

int main() {
int x, y;
cin >> x >> y;
Point p1(x, y); // 构造函数传入x,y坐标
cout << p1.getX() << " " << p1.getY() << endl;
Point p2(x); // 构造函数只传x坐标,默认y为0
cout << p2.getX() << " " << p2.getY() << endl;
Point p3; // 构造函数不传参数,默认x和y都为0
cout << p3.getX() << " " << p3.getY() << endl;
return 0;
}

输入样例:

输入x和y坐标。例如:

21 2

输出样例:

分别输出三个点p1, p2, p3的坐标。例如:

21 2
21 0
0 0

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Point {
private:
int a,b;
public:
Point(int m,int n)
{
a=m;
b=n;
}
Point(int m)
{
a=m;
b=0;
}
Point()
{
a=0;
b=0;
}
int getX()
{return a;}
int getY()
{return b;}
};

6-3 你好,构造函数和析构函数

C++-6-3

作者 向训文

单位 惠州学院

你知道构造函数和析构函数什么时候调用吗?编写Person类:

  • 在构造函数中输出mark1或mark2,以及这个人的年龄
  • 在析构函数中输出mark1或mark2,以及这个人的年龄

裁判测试程序样例:

#include<iostream> 
using namespace std;

// 请在这里填写答案

int main() {
int age1, age2;
cin >> age1 >> age2;
Person p1(age1), p2(age2);
return 0;
}

输入样例:

输入两个人的年龄。例如:

18 19

输出样例:

在这里给出相应的输出。例如:

mark1: 18
mark1: 19
mark2: 19
mark2: 18

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class Person{
private:
int a;
public:
Person(int m);
~Person();
};
Person::Person(int m)
{
cout<<"mark1: "<<m<<endl;
a=m;
}
Person::~Person()
{
cout<<"mark2: "<<a<<endl;
}

四、2024.3.16——2024春面向对象程序设计作业03

C++-4

(1)单选题

C++-4.1

2-1(C)

在声明类时,下面的说法正确的是( )。

A.可以在类的声明中给数据成员赋初值

B.数据成员的类型可以是register

C.private、public、protected可以按任意顺序出现

D.没有用private、public、protected定义的数据成员是公有成员

2-2(A)

下列关于类定义的说法中,正确的是

A.类定义中包括数据成员和函数成员的声明

B.类成员的缺省访问权限是保护的

C.数据成员必须被声明为私有的

D.成员函数只能在类体外进行定义

2-3(A)

类成员默认的访问属性

类成员默认的访问属性为 ▁▁▁▁▁。

A.private

B.protected

C.public

D.friend

2-4(B)

关于封装性

在 C++ 中,实现封装性需借助于 ▁▁▁▁▁。

A.枚举

B.类

C.数组

D.函数

2-5(C)

关于面向对象程序设计方法,下列说法中正确的是

A.在数据处理过程中,采用的是自顶向下、分而治之的方法

B.将整个程序按功能划分为几个可独立编程的子模块

C.以“对象”和“数据”为中心

D.数据和处理数据的过程代码是分离的、相互独立的实体

(2)程序填空题

C++-4.2

类的意义1:将描述类别的属性、行为放在一起,表现事务

作者 郑远

单位 中国民用航空飞行学院

设计一个圆类,求圆的周长

#include<iostream>
const double PI = 3.14;
using namespace std;
//1、封装的意义
//将属性和行为作为一个整体,用来表现生活中的事物
//封装一个圆类,求圆的周长
//class代表设计一个类,后面跟着的是类名
class Circle
{
public://访问权限 公共的权限
float m_r;
//获取到圆的周长
double calculateZC()
{
//2 * pi * r
//获取圆的周长
return 2 * PI * m_r;
}
};
int main() {
//通过圆类,创建圆的对象
// c1就是一个具体的圆
Circle c1;
c1.m_r = 10; //给圆对象的半径 进行赋值操作
//2 * pi * 10 = = 62.8
cout << "圆的周长为: " << c1.calculateZC() << endl;
return 0;
}

答案:

第一空:

public:

第二空:

float m_r;

第三空:

2 * PI  * m_r;

(3)函数题

C++-4.3

6-1 定义point类

6-1

作者 王荣海

单位 泉州师范学院

请编写point类的全部代码,实现程序运行后输出结果为:

op1 i=10 op1 j=20

point类定义框架:

class point {
private:
// 这里编写数据成员声明代码
public:
//这里编写相关成员函数实现代码
};

测试程序样例:

#include <iostream>
#include <string>
using namespace std;
/*point类代码将被插入在这个位置*/
int main() {
point op1;
int i,j;
op1.setpoint(10,20);
i=op1.getx();
j=op1.gety();
cout<<"op1 i="<<i<<" op1 j="<<j<<endl;
return 0;
}

输入样例:

无

输出样例:

op1 i=10 op1 j=20

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

class point {
private:
int x,y,i,j;
public:
void setpoint(int x,int y)
{
i=x;
j=y;
return;
}
int getx()
{
return i;
}
int gety()
{
return j;
}
};

三、2024.3.07——2024春面向对象程序设计作业02

C++-3

(1)判断题

C++-3.1

1-1(T)

在C++中,以“//”(不包括双引号)开始的注释内容只在本行起作用。

1-2(F)

C++中,输入运算符“>>”又称为插入运算符。

1-3(T)

C++允许变量声明与可执行语句在程序中交替出现。

1-4(F)

在C++中,结构名不可直接作为类型名,在定义变量时,必须在结构名前冠以struct。

1-5(T)

在C++局部变量的作用域内,可用::对被屏蔽的同名全局变量进行访问。

(2)单选题

C++-3.2

2-1(D)

下列语句中错误的是( )。

A.int *p = new int(20);

B.int *p = new int[20];

C.int *p = new int;

D.int *p = new int[40] (10);

2-2(A)

重载函数在调用时选择的依据中,( )是错误的。

A.函数的返回类型

B.函数名字

C.函数参数个数

D.函数参数的类型

2-3(B)

在( )情况下适宜采用内联函数。

A.函数代码多,频繁调用

B.函数代码少,频繁调用

C.函数体含有递归语句

D.函数体含有循环语句

2-4(B)

在C++中,关于下列设置默认参数值的描述中,( )是正确的。

A.不允许设置默认参数值

B.在指定了默认值的参数右边,不能出现没有指定默认值的参数

C.只能在函数的定义性声明中指定参数的默认值

D.设置默认参数值时,必须全部都设置

2-5(D)

关于new运算符的下列描述中,( )是错误的。

A.它可以用来动态创建对象和对象数组

B.使用它创建的对象或对象数组可以使用运算符delete删除

C.使用它创建对象时要调用构造函数

D.使用它创建对象数组时必须指定初始值

2-6(C)

关于delete运算符的下列描述中,( )是错误的。

A.它必须用于new返回的指针

B.使用它删除对象时要调用析构函数

C.对一个指针可以使用多次该运算符

D.指针名前只有一对方括号符号,不管所删除数组的维数

2-7(D)

假设已经有定义“const char * const name=”Zhang”;”,下面的语句中正确的是( )。

A.name[3]=’a’;

B.name=”lin”;

C.name=new char[5];

D.cout<<name[3];

2-8(A)

假设已经有定义“const char *name=”Zhang”;”,下面的语句中错误的是( )。

A.name[2]=’q’;

B.name=”Li”;

C.name=new char [6];

D.name=new char(‘q’);

2-9(C)

下列描述中,( )是错误的。

A.内联函数主要解决程序的运行效率问题

B.内联函数的定义必须出现在内联函数第一次被调用之前

C.内联函数中可以包括各种语句

D.对内联函数不可以进行异常接口声明

2-10(D)

下面的类型声明中正确的是( )。

A.int &b[4];

B.int & *q;

C.int && p;

D.int j, *p=&j;

(3)程序填空题

C++-3.3

5-1 交换两个数

C++-5-1

作者 王荣海

单位 泉州师范学院

本题要求输入两个数,输出交换后的结果:

输入:  
10 5
输出
5 10
#include <iostream>
using namespace std;
void f(int &m,int &n)
{
int temp;
temp=m;
m=n;
n=temp;
}
int main() {
int a,b;
cin>>a>>b;
f(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}

答案:

第一空:

m=n;

第二空:

f(a,b);

5-2 作用域运算符的使用

C++-5-2

作者 wrh

单位 泉州师范学院

以下是关于作用域运算符使用的程序,请完成程序填空。

输入:
100
输出结果:
102
#include <iostream>
using namespace std;
int i=99;
int main() {
int i;
cin>>i;
::i=102;
cout<<::i<<endl;
return 0;
}

答案:

第一空:

::i=102;

5-3 引用作为函数参数的应用

C++-5-3

作者 wrh

单位 泉州师范学院

以下是关于引用作为函数参数的应用的程序,请完成程序填空。

输入:
5 8
输出结果:
5 5
#include <iostream>
using namespace std;
void f(int m,int &n){
int temp;
temp=m;
m=n;
n=temp;
}
int main() {
int a,b;
cin>>a>>b;
f(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}

答案:

第一空:

int &n

第二空:

int a,b;

第三空:

f(a,b);

(4)函数题

C++-3.4

6-1 你好,new和delete

6-1

作者 向训文

单位 惠州学院

完善程序,使用new动态创建数组,并输入n个数,存储在数组中:

裁判测试程序样例:

#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
// 请将答案填在这里
for (int i = 0; i < n; ++i) {
cout << p[i] << " ";
}
cout << endl;
delete []p;
return 0;
}

输入样例:

第一行为接下来要输入的整数的个数,第二行为n个整数。例如:

3
1 2 3

输出样例:

输出n个整数的值。例如:

1 2 3

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int *p=new int(n);
for(int i=0;i<n;i++)
cin>>p[i];

6-2 你好,函数重载2

6-2

作者 向训文

单位 惠州学院

编写两个myMax函数,分别用来计算两个、三个整数的最大值:

裁判测试程序样例:

#include <iostream>
using namespace std;

// 请将答案填写在这里

int main()
{
int x, y, z;
cin >> x >> y >> z;
cout << myMax(x, y) << endl; // 输出前两个数的最大值
cout << myMax(x, y, z) << endl; // 输出三个数的最大值
return 0;
}

输入样例:

输入三个整数。例如:

5 6 12

输出样例:

分别输出前两个数的最大值、三个数的最大值。例如:

6
12

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int myMax(int x,int y)
{
return x>y?x:y;
}
int myMax(int x,int y,int z)
{
int a;
a=x>y?x:y;
return a>z?a:z;
}

二、2024.3.04——2024春面向对象程序设计上机练习01

C++-2

(1)程序填空题

C++-2.1

5-1加法函数重载

作者 王荣海

单位 泉州师范学院

本题目实现对2个数相加及3个数相加的函数重载,输入3个数,分别输出前两个数及3个数的和,请把空缺的语句补上。

输入样例:
1 2 3
相应输出样例:
1+2=3
1+2+3=6
#include<iostream>
using namespace std;
int add(int x,int y)
{
return x+y;
}
int add(int x,int y,int z)
{
return x+y+z;
}
int main() {
int a,b,c;
cin>>a>>b>>c;
cout<<a<<'+'<<b<<'='<<add(a,b)<<endl;
cout<<a<<'+'<<b<<'+'<<c<<'='<<add(a,b,c)<<endl;
return 0;
}

答案:

第一空:

return x+y;

第二空:

return x+y+z;

(2)函数题

C++-2.2

6-1 带默认形参值的函数

6-1

作者 李廷元

单位 中国民用航空飞行学院

设计一个带默认形参值的函数add,该函数有三个参数,可以实现三个整数类型的参数相加的操作,函数返回相加的结果。默认形参值从右至左分别是30、20。

裁判测试程序样例:

#include <iostream>
using namespace std;

/* 请在这里填写答案 */


int main()
{
int a, b, c;

cin >> a >> b >> c;

cout << add(a) << endl;
cout << add(a, b) << endl;
cout << add(a, b, c) << endl;

return 0;
}

输入样例:

1 2 3

输出样例:

51
33
6

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

答案:

int add(int a,int b=20,int c=30)
{
return a+b+c;
}

(3)编程题

C++-2.3

7-1 C++风格输入输出字符串

7-1

作者 wrh

单位 泉州师范学院

请使用C++风格的输入输出操作,编程实现以下功能:

(1)输入一个字符串

(2)输出The string is +刚才输入的字符串+.

输入格式:

Hello

输出格式:

The string is Hello. (输出最后有一个.)

输入样例:

输入内容如下:

Hello

输出样例:

相应的输出内容如下:

The string is Hello.

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <iostream>
using namespace std;
#include <string>
int main()
{
string a;
cin >> a;
cout << "The string is " << a << "." << endl;
}

一、2024.2.29——2024春面向对象程序设计作业01

C++-1

(1)判断题

C++-1.1

1.1(F)

面向对象程序设计范型的主要特征是:
程序=过程+调用

1.2(T)

同一个对象可以接收不同形式的多个消息,做出不同的响应。

1.3(T)

面向过程的程序设计思想的核心是功能的分解

1.4(T)

面向对象程序一般由类的定义和类的使用两部分组成

1.5(F)

多继承是指每个派生类直接继承了一个基类的多个特征

(2)选择题

C++-1.2

2.1(C)

将私有元素和实现操作的内部细节隐藏起来,并能管理自己的内部状态是指对象的()。

A.模块独立性

B.动态连接性

C.封装性

D.易维护性

2.2(B)

对象通过消息传递机制将对象动态地联系在一起的特性是指()

A.模块独立性

B.动态连接性

C.封装性

D.易维护性

2.3(D)

对象发送消息时,以下不属于消息应包括的内容的是()。

A.接收者的名字

B.请求的方法

C.一个或多个参数

D.发送者的名字

(3)编程题

C++-1.3

7-1 C++风格输入输出(两个整数相减)

7-1

作者 wrh

单位 泉州师范学院

请使用C++风格的输入输出编写程序,实现输入两个整数(以空格分隔),输出这两个整数相减的结果。

输入格式:

5 3

输出格式:

2

输入样例:

在这里给出一组输入。例如:

5 3

输出样例:

在这里给出相应的输出。例如:

2

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
int a,b;
cin >> a >> b;
cout << a-b << endl;
system("pause");
return 0;
}

7-2 C++类及C++风格输入输出(两个整数相减)

7-2

作者 wrh

单位 泉州师范学院

请使用C++类及C++风格的输入输出编写程序,实现输入两个整数(以空格分隔),输出这两个整数相减的结果。

输入格式:

5 3

输出格式:

2

输入样例:

在这里给出一组输入。例如:

5 3

输出样例:

在这里给出相应的输出。例如:

2

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

栈限制:8192 KB

答案:

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
int a,b;
cin >> a >> b;
cout << a-b << endl;
system("pause");
return 0;
}