【PTA/C++】编程题

✅文章中的题解仅作参考,如果有对代码内容的建议或更优解法欢迎指正和交流!

R7-1 找出3个字符串中最大的字符串

利用3×20的二维字符数组存放3个字符串,找出其中最大的字符串并输出。

输入格式:

在3行分别输入3个字符串,在字符串中不要出现换行符,空格,制表符

输出格式:

在两行中按照“The largest string is:(换行)最大字符串”的顺序输出。

输入样例:

as
qwer
zxc

输出样例:

The largest string is:
zxc

AC:

#include<iostream>
#include <cstring>
//字符数组:#include <cstring>
//std::string: #include<string>

using namespace std;

int main(){
char str[3][20];
char largest[20];
for (int i = 0; i < 3; i++) {
    cin >> str[i];
}
//wrong:cin>>str;

strcpy(largest,str[0]);
//wrong:largest=str[0];

if(strcmp(largest,str[1])<0) strcpy(largest, str[1]);
if(strcmp(largest,str[2])<0) strcpy(largest, str[2]);

cout << "The largest string is:" << endl;
cout<<largest<<endl;
return 0;

}

R7-2 查验身份证

一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:

首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M的值:

Z:0 1 2 3 4 5 6 7 8 9 10
M:1 0 X 9 8 7 6 5 4 3 2

现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。

输入格式:

输入第一行给出正整数N(≤100)是输入的身份证号码的个数。随后N行,每行给出1个18位身份证号码。

输出格式:

按照输入的顺序每行输出1个有问题的身份证号码。这里并不检验前17位是否合理,只检查前17位是否全为数字且最后1位校验码计算准确。如果所有号码都正常,则输出All passed

输入样例1:

4
320124198808240056
12010X198901011234
110108196711301866
37070419881216001X

输出样例1:

12010X198901011234
110108196711301866
37070419881216001X

输入样例2:

2
320124198808240056
110108196711301862

输出样例2:

All passed

 AC:

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

int main() {
    int n;
    cin >> n;

 
    vector<vector<char>> num(n, vector<char>(18));
    //  使用 vector 实现动态二维数组
    int temp = 0;  
    // 初始化 temp

    for (int i = 0; i < n; i++) {
    //使用嵌套循环逐行逐列输入
        for (int j = 0; j < 17; j++) {
            cin >> num[i][j];
        }
        cin >> num[i][17]; // 单独输入最后一位校验码

        int num_Z = (
        //将字符转换为数字,wrong:num[i][0]*7+num[i][1]*9
        //输入流 cin 会将键盘输入的字符视为字符类型。
//若直接使用字符进行数学运算(如 '1' * 7),实际上会使用字符的 ASCII 码值('1' 的 ASCII 码为 //49),导致计算结果错误。
            (num[i][0] - '0') * 7 + (num[i][1] - '0') * 9 + (num[i][2] - '0') * 10 +
            (num[i][3] - '0') * 5 + (num[i][4] - '0') * 8 + (num[i][5] - '0') * 4 +
            (num[i][6] - '0') * 2 + (num[i][7] - '0') * 1 + (num[i][8] - '0') * 6 +
            (num[i][9] - '0') * 3 + (num[i][10] - '0') * 7 + (num[i][11] - '0') * 9 +
            (num[i][12] - '0') * 10 + (num[i][13] - '0') * 5 + (num[i][14] - '0') * 8 +
            (num[i][15] - '0') * 4 + (num[i][16] - '0') * 2
        ) % 11;

        char num_M = '\0'; // 初始化 num_M
        switch (num_Z) {
            case 0: num_M = '1'; break;
            case 1: num_M = '0'; break;
            case 2: num_M = 'X'; break;
            case 3: num_M = '9'; break;
            case 4: num_M = '8'; break;
            case 5: num_M = '7'; break;
            case 6: num_M = '6'; break;
            case 7: num_M = '5'; break;
            case 8: num_M = '4'; break;
            case 9: num_M = '3'; break;
            case 10: num_M = '2'; break;
            default: break;
        }

        if (num[i][17] != num_M) {
            for (int j = 0; j < 18; j++) {
                cout << num[i][j];
            }
            cout << endl;
            temp = 1;
        }
    }

    if (temp == 0) cout << "All passed" << endl;

    return 0;
}

R7-3 考试座位号

每个 PAT 考生在参加考试时都会被分配两个座位号,一个是试机座位,一个是考试座位。正常情况下,考生在入场时先得到试机座位号码,入座进入试机状态后,系统会显示该考生的考试座位号码,考试时考生需要换到考试座位就座。但有些考生迟到了,试机已经结束,他们只能拿着领到的试机座位号码求助于你,从后台查出他们的考试座位号码。

输入格式:

输入第一行给出一个正整数 N(≤1000),随后 N 行,每行给出一个考生的信息:准考证号 试机座位号 考试座位号。其中准考证号由 16 位数字组成,座位从 1 到 N 编号。输入保证每个人的准考证号都不同,并且任何时候都不会把两个人分配到同一个座位上。

考生信息之后,给出一个正整数 M(≤N),随后一行中给出 M 个待查询的试机座位号码,以空格分隔。

输出格式:

对应每个需要查询的试机座位号码,在一行中输出对应考生的准考证号和考试座位号码,中间用 1 个空格分隔。

输入样例:

4
3310120150912233 2 4
3310120150912119 4 1
3310120150912126 1 3
3310120150912002 3 2
2
3 4

输出样例:

3310120150912002 2
3310120150912119 1

AC:

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

const int MAXN = 1005;

// 定义结构体来存储考生信息
struct Student {
    string examNumber;  // 准考证号
    int testSeat;       // 试机座位号
    int examSeat;       // 考试座位号
};

int main() {
    int n;
    cin >> n;

    // 定义一个数组来存储所有考生的信息
    Student students[MAXN];

    // 读取每个考生的信息并存储到数组中
    for (int i = 0; i < n; ++i) {
        cin >> students[i].examNumber >> students[i].testSeat >> students[i].examSeat;
    }

    int m;
    cin >> m;

    // 处理每个查询
    for (int i = 0; i < m; ++i) {
        int testSeat;
        cin >> testSeat;

        // 遍历数组查找对应的考生信息
        for (int j = 0; j < n; ++j) {
            if (students[j].testSeat == testSeat) {
                cout << students[j].examNumber << " " << students[j].examSeat << endl;
                break;
            }
        }
    }

    return 0;
}

R7-4 掉入陷阱的数字

对任意一个自然数N0​,先将其各位数字相加求和,再将其和乘以3后加上1,变成一个新自然数N1​;然后对N1​重复这种操作,可以产生新自然数N2​;……多次重复这种操作,运算结果最终会得到一个固定不变的数Nk​,就像掉入一个数字“陷阱”。

本题要求对输入的自然数,给出其掉入“陷阱”的过程。

输入格式:

在一行内给出一个自然数N0​(N0​<30000)。

输出格式:

对于输入的N0​,逐行输出其掉入陷阱的步骤。第i行描述N掉入陷阱的第i步,格式为: i:Ni​ (i≥1)。当某一步得到的自然数结果Nk​(k≥1)与上一步Nk−1​相同时,停止输出。

输入样例:

5

输出样例:

1:16
2:22
3:13
4:13

AC :

#include<iostream>
using namespace std;

int main(){
	
	int n0,n1;
	cin >> n0;
	
	int i=1;
	
	
	while(1){
		int sum=0;
		int temp=n0;
		while(temp!=0){
			sum += temp%10;
			temp /= 10;
		}
		n1=sum*3 +1;
		cout<<i<<":"<<n1<<endl;
		
		if (n0 == n1) {
            break;  
        }
        n0 = n1;
		i++;
	}
	
	return 0;
	
}

R7-5 鸡兔同笼

一个笼子里面关了鸡和兔子(鸡有2只脚,兔子有4只脚,没有例外)。已经知道了笼子里面脚的总数a,问笼子里面至少有多少只动物,至多有多少只动物

输入格式:

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a (a < 32768)。

输出格式:

n行,每行输出对应一个输入。输出是两个正整数,第一个是最少的动物数,第二个是最多的动物数,两个正整数用空格分开。如果没有满足要求的情况出现,则输出2个0。

输入样例:

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

2 
3
20

输出样例:

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

0 0
5 10

AC:

#include<iostream>
using namespace std;

int main(){
	
	int N,n1=0,n2=0;
	cin >>N;
	int lastnum,mostnum;
	int n[N];
	for(int i=0;i<N;i++){
		cin>>n[i];
    }
	
	for(int i=0;i<N;i++){
		n1=n2=n[i];
		if(n[i]%2!=0){
			cout <<0<<" "<<0<<endl;
			continue;
		}
	  	else{
	  		lastnum= n1 /4 + (n1 %4)/2;
	  		mostnum= n2 /2 + (n2 %2)/4;
		}
	cout <<lastnum<<" "<<mostnum<<endl;
    }
	
	return 0;
}

R7-6 英文单词排序

本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。

输入格式:

输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。

输出格式:

输出为排序后的结果,每个单词后面都额外输出一个空格。

输入样例:

blue
red
yellow
green
purple
#

输出样例:

red blue green yellow purple 

AC :

1.冒泡排序:一种简单的排序算法,它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> words;
    std::string word;

    // 读取输入,直到遇到 # 结束
    while (std::cin >> word && word != "#") {
        words.push_back(word);
    }

    int n = words.size();
    // 冒泡排序
    for (int i = 0; i < n - 1; ++i) {
        for (int j = 0; j < n - i - 1; ++j) {
            if (words[j].length() > words[j + 1].length()) {
                std::swap(words[j], words[j + 1]);
            }
        }
    }

    // 输出排序后的单词,每个单词后加一个空格
    for (const auto& w : words) {
        std::cout << w << " ";
    }
    std::cout << std::endl;

    return 0;
}

2.选择排序:一种简单直观的排序算法,它首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> words;
    std::string word;

    // 读取输入,直到遇到 # 结束
    while (std::cin >> word && word != "#") {
        words.push_back(word);
    }

    int n = words.size();
    // 选择排序
    for (int i = 0; i < n - 1; ++i) {
        int minIndex = i;
        for (int j = i + 1; j < n; ++j) {
            if (words[j].length() < words[minIndex].length()) {
                minIndex = j;
            }
        }
        if (minIndex != i) {
            std::swap(words[i], words[minIndex]);
        }
    }

    // 输出排序后的单词,每个单词后加一个空格
    for (const auto& w : words) {
        std::cout << w << " ";
    }
    std::cout << std::endl;

    return 0;
}

3.插入排序:一种简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> words;
    std::string word;

    // 读取输入,直到遇到 # 结束
    while (std::cin >> word && word != "#") {
        words.push_back(word);
    }

    int n = words.size();
    // 插入排序
    for (int i = 1; i < n; ++i) {
        std::string key = words[i];
        int j = i - 1;
        while (j >= 0 && words[j].length() > key.length()) {
            words[j + 1] = words[j];
            --j;
        }
        words[j + 1] = key;
    }

    // 输出排序后的单词,每个单词后加一个空格
    for (const auto& w : words) {
        std::cout << w << " ";
    }
    std::cout << std::endl;

    return 0;
}

R7-7 最长对称子串

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

AC:

 1.中心扩展法:

expandAroundCenter 函数:该函数以 left 和 right 为中心向两边扩展,只要 s[left] 等于 s[right] 且不越界,就继续扩展,最后返回对称子串的长度。

longestPalindromeLength 函数:遍历字符串中的每个字符,分别以该字符为中心(奇数长度对称子串)和该字符及其下一个字符为中心(偶数长度对称子串)调用 expandAroundCenter 函数进行扩展,记录并返回最长对称子串的长度。

main 函数:读取输入的字符串,调用 longestPalindromeLength 函数计算最长对称子串的长度并输出。

#include <iostream>
#include <string>
#include <algorithm>

// 中心扩展函数
int expandAroundCenter(const std::string& s, int left, int right) {
    while (left >= 0 && right < s.length() && s[left] == s[right]) {
        left--;
        right++;
    }
    return right - left - 1;
}

// 计算最长对称子串长度
int longestPalindromeLength(const std::string& s) {
    if (s.length() < 2) {
        return s.length();
    }
    int maxLength = 0;
    for (int i = 0; i < s.length(); ++i) {
        // 以单个字符为中心扩展(奇数长度对称子串)
        int len1 = expandAroundCenter(s, i, i);
        // 以两个字符为中心扩展(偶数长度对称子串)
        int len2 = expandAroundCenter(s, i, i + 1);
        maxLength = std::max({maxLength, len1, len2});
    }
    return maxLength;
}

int main() {
    std::string s;
    std::getline(std::cin, s);
    std::cout << longestPalindromeLength(s) << std::endl;
    return 0;
}

2.动态规划法:

初始化 dp 数组:单个字符都是对称子串,所以 dp[i][i] 初始化为 true。同时,检查长度为 2 的子串,如果两个字符相等,则对应的 dp[i][i + 1] 为 true

填充 dp 数组:对于长度大于 2 的子串,若 s[i] 等于 s[j] 且 dp[i + 1][j - 1] 为 true,则 dp[i][j] 为 true,并更新最长对称子串的长度。

main 函数:读取输入的字符串,调用 longestPalindromeLength 函数计算最长对称子串的长度并输出。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

// 计算最长对称子串长度
int longestPalindromeLength(const std::string& s) {
    int n = s.length();
    if (n < 2) {
        return n;
    }
    int maxLength = 1;
    std::vector<std::vector<bool>> dp(n, std::vector<bool>(n, false));

    // 单个字符都是对称子串
    for (int i = 0; i < n; ++i) {
        dp[i][i] = true;
    }

    // 检查长度为 2 的子串
    for (int i = 0; i < n - 1; ++i) {
        if (s[i] == s[i + 1]) {
            dp[i][i + 1] = true;
            maxLength = 2;
        }
    }

    // 检查长度大于 2 的子串
    for (int length = 3; length <= n; ++length) {
        for (int i = 0; i <= n - length; ++i) {
            int j = i + length - 1;
            if (s[i] == s[j] && dp[i + 1][j - 1]) {
                dp[i][j] = true;
                maxLength = length;
            }
        }
    }

    return maxLength;
}

int main() {
    std::string s;
    std::getline(std::cin, s);
    std::cout << longestPalindromeLength(s) << std::endl;
    return 0;
}

R7-8 停车场管理

设有一个可以停放n辆汽车的狭长停车场,它只有一个大门可以供车辆进出。车辆按到达停车场时间的先后次序依次从停车场最里面向大门口处停放 (即最先到达的第一辆车停放在停车场的最里面) 。如果停车场已放满n辆车,则以后到达的车辆只能在停车场大门外的便道上等待,一旦停车场内有车开走,则排在便道上的第一辆车可以进入停车场。停车场内如有某辆车要开走,则在它之后进入停车场的车都必须先退出停车场为它让路,待其开出停车场后,这些车辆再依原来的次序进场。每辆车在离开停车场时,都应根据它在停车场内停留的时间长短交费,停留在便道上的车不收停车费。编写程序对该停车场进行管理。

输入格式:

先输入一个整数n(n<=10),再输入若干组数据,每组数据包括三个数据项:汽车到达或离开的信息(A表示到达、D表示离开、E表示结束)、汽车号码、汽车到达或离开的时刻。

输出格式:

若有车辆到达,则输出该汽车的停车位置;若有车辆离开,则输出该汽车在停车场内停留的时间。如果汔车号码不存在,输出the car not in park

输入样例:

3
A 1 1 
A 2 2
A 3 3
D 1 4
A 4 5
A 5 6
D 4 7
D 5 8
E 0 0

输出样例:

car#1 in parking space #1
car#2 in parking space #2
car#3 in parking space #3
car#1 out,parking time 3
car#4 in parking space #3
car#5 waiting
car#4 out,parking time 2
car#5 in parking space #3
car#5 out,parking time 1

AC: 

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

// 定义汽车结构体
struct Car {
    int number;  // 汽车号码
    int arrivalTime;  // 到达时间
    int position;  // 停车位置
    Car(int num, int time, int pos) : number(num), arrivalTime(time), position(pos) {}
};

int main() {
    int n;
    cin >> n;

    vector<Car> parkingLot;  // 停车场
    queue<Car> waitingQueue;  // 便道等待队列

    char action;
    int carNumber, time;
    while (true) {
        cin >> action >> carNumber >> time;
        if (action == 'E') {
            break;
        }

        if (action == 'A') {
            if (parkingLot.size() < n) {
                // 停车场有空位,车辆进入停车场
                int position = parkingLot.size() + 1;
                parkingLot.emplace_back(carNumber, time, position);
                cout << "car#" << carNumber << " in parking space #" << position << endl;
            } else {
                // 停车场已满,车辆进入便道等待
                waitingQueue.emplace(carNumber, time, -1);
                cout << "car#" << carNumber << " waiting" << endl;
            }
        } else if (action == 'D') {
            bool found = false;
            int index = -1;
            // 查找要离开的车辆
            for (int i = 0; i < parkingLot.size(); ++i) {
                if (parkingLot[i].number == carNumber) {
                    found = true;
                    index = i;
                    break;
                }
            }

            if (!found) {
                cout << "the car not in park" << endl;
            } else {
                // 计算停车时间
                int parkingTime = time - parkingLot[index].arrivalTime;
                cout << "car#" << carNumber << " out,parking time " << parkingTime << endl;

                // 要离开的车辆后面的车辆先退出停车场
                vector<Car> temp;
                for (int i = parkingLot.size() - 1; i > index; --i) {
                    temp.push_back(parkingLot[i]);
                }
                parkingLot.erase(parkingLot.begin() + index, parkingLot.end());

                // 调整剩余车辆的停车位置
                for (int i = 0; i < parkingLot.size(); ++i) {
                    parkingLot[i].position = i + 1;
                }

                // 等待队列中的第一辆车进入停车场
                if (!waitingQueue.empty()) {
                    Car nextCar = waitingQueue.front();
                    waitingQueue.pop();
                    nextCar.arrivalTime = time;
                    nextCar.position = parkingLot.size() + 1;
                    parkingLot.push_back(nextCar);
                    cout << "car#" << nextCar.number << " in parking space #" << nextCar.position << endl;
                }

                // 原来退出的车辆再依次进入停车场
                for (int i = temp.size() - 1; i >= 0; --i) {
                    temp[i].position = parkingLot.size() + 1;
                    parkingLot.push_back(temp[i]);
                }
            }
        }
    }

    return 0;
}

R7-9 使用函数删除字符串中的字符

输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算:

输入一个字符串 str,再输入一个字符 c,将字符串 str 中出现的所有字符 c 删除。

要求定义并调用函数delchar(str,c), 它的功能是将字符串 str 中出现的所有 c 字符删除,函数形参str的类型是字符指针,形参c的类型是char,函数类型是void。

输入输出示例:括号内为说明,无需输入输出

输入样例:

3               (repeat=3)
happy new year  (字符串"happy new year")
a               (待删除的字符'a')
bee             (字符串"bee")
e               (待删除的字符'e')
111211          (字符串"111211")
1               (待删除的字符'1')

输出样例:

result: hppy new yer    (字符串"happy new year"中的字符'a'都被删除)
result: b               (字符串"bee"中的字符'e'都被删除)
result: 2               (字符串"111211"中的字符'1'都被删除)

 AC:

#include <iostream>
#include <string>

// 定义 delchar 函数,用于删除字符串中指定的字符
void delchar(std::string& str, char c) {
    std::string result;
    for (char ch : str) {
        if (ch != c) {
            result += ch;
        }
    }
    str = result;
}

int main() {
    int repeat;
    std::cin >> repeat;
    std::cin.ignore(); // 忽略掉 cin 读取整数后留在缓冲区的换行符

    for (int i = 0; i < repeat; ++i) {
        std::string str;
        char c;

        std::getline(std::cin, str);
        std::cin.get(c);
        std::cin.ignore(); // 忽略掉 cin.get 读取字符后留在缓冲区的换行符

        delchar(str, c);
        std::cout << "result: " << str << std::endl;
    }

    return 0;
}

R7-10 利用指针返回多个函数值

读入n个整数,调用max_min()函数求这n个数中的最大值和最小值。

输入格式:

输入有两行:
第一行是n值;
第二行是n个数。

输出格式:

输出最大值和最小值。

输入样例:

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

5
8 9 12 0 3

输出样例:

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

max = 12
min = 0

AC:

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

void max_min(const vector<int>& arr) {
    int max, min;
    max = min = arr[0];
    for (size_t i = 1; i < arr.size(); ++i) {
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    cout << "max = " << max << endl;
    cout << "min = " << min << endl;
}

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
 
    max_min(a);
    return 0;
}

R7-11 二维数组每行排序

一个4×5的整型二维数组,从键盘输入数据,并对该数组的每一行按从小到大的顺序排列后输出。

输入格式:

输入4行5列的矩阵,每行第一个数前没有空格,每行的每个数之间各有一个空格。

输出格式:

输出4行5列的矩阵,每行第一个数前没有空格,每个数输出占4列列宽。

输入样例:

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

输出样例:

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

AC:

#include <iostream>
#include <iomanip>
#include <algorithm>

const int ROWS = 4;
const int COLS = 5;

int main() {
    
    int arr[ROWS][COLS];
    
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cin >> arr[i][j];
        }
    }

    // 对数组的每一行按从小到大的顺序排列
    for (int i = 0; i < ROWS; ++i) {
        std::sort(arr[i], arr[i] + COLS);
    }

    // 输出排序后的数组
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cout << std::setw(4) << arr[i][j];
        }
        std::cout << std::endl;
    }

    return 0;
}

R7-12 找出不是两个数组共有的元素

给定两个整型数组,本题要求找出不是两者共有的元素。

输入格式:

输入分别在两行中给出两个整型数组,每行先给出正整数N(≤20),随后是N个整数,其间以空格分隔。

输出格式:

在一行中按照数字给出的顺序输出不是两数组共有的元素,数字间以空格分隔,但行末不得有多余的空格。题目保证至少存在一个这样的数字。同一数字不重复输出。

输入样例:

10 3 -5 2 8 0 3 5 -15 9 100
11 6 4 8 2 6 -5 9 0 100 8 1

输出样例:

3 5 -15 6 4 1

AC: 

#include <iostream>
using namespace std;

// 检查元素是否已经在结果数组中
bool isInResult(int num, int result[], int resultSize) {
    for (int i = 0; i < resultSize; ++i) {
        if (result[i] == num) {
            return true;
        }
    }
    return false;
}

// 检查元素是否在另一个数组中
bool isInArray(int num, int arr[], int arrSize) {
    for (int i = 0; i < arrSize; ++i) {
        if (arr[i] == num) {
            return true;
        }
    }
    return false;
}

int main() {
    int n1, n2;
    int arr1[20], arr2[20];
    int result[40];  // 用于存储结果,最大可能长度为两个数组长度之和
    int resultSize = 0;


    cin >> n1;
    for (int i = 0; i < n1; ++i) {
        cin >> arr1[i];
    }
    cin >> n2;
    for (int i = 0; i < n2; ++i) {
        cin >> arr2[i];
    }

    // 遍历第一个数组,找出不在第二个数组中的元素
    for (int i = 0; i < n1; ++i) {
        if (!isInArray(arr1[i], arr2, n2) && !isInResult(arr1[i], result, resultSize)) {
            result[resultSize++] = arr1[i];
        }
    }

    // 遍历第二个数组,找出不在第一个数组中的元素
    for (int i = 0; i < n2; ++i) {
        if (!isInArray(arr2[i], arr1, n1) && !isInResult(arr2[i], result, resultSize)) {
            result[resultSize++] = arr2[i];
        }
    }

    // 输出结果
    for (int i = 0; i < resultSize; ++i) {
        if (i > 0) {
            cout << " ";
        }
        cout << result[i];
    }
    cout << endl;

    return 0;
}

R7-13 报数(约瑟夫环问题)

输入两个正整数 n 和 m( (1<m<n<=50)),有 n 个人围成一圈,按顺序从 1 到 n 编号。从第一个人开始报数,报数 m 的人退出圈子,下一个人从 1 开始重新报数,报数 m 的人退出圈子。如此循环,直到留下最后一个人。请按退出顺序输出退出圈子的人的编号,以及最后一个人的编号。

提示:将每个人的编号存入数组,从第一个人开始报数,输出报数 m 的人的编号,并将该编号清除为0,重复这样的操作直至只剩下一个不为0的数,该数就是最后一个人的编号。

输入输出示例:括号内为说明,无需输入输出

输入样例:

5               (n个人报数,n=5)
3               (报数m=3)

输出样例:

No1: 3          (第1个退出圈子的人编号是3)
No2: 1            (第2个退出圈子的人编号是1)
No3: 5            (第3个退出圈子的人编号是5)
No4: 2            (第4个退出圈子的人编号是2)
Last No is: 4   (最后一个人的编号是4)

 AC:

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

int main() {
    int n, m;
    cin >> n >> m;

    vector<int> people(n);
    for (int i = 0; i < n; ++i) {
        people[i] = i + 1;
    }

    int index = 0;
    int count = 0;
    int outCount = 0;
    vector<int> outOrder;

    while (outCount < n - 1) {
        if (people[index] != 0) {
            count++;
            if (count == m) {
                outOrder.push_back(people[index]);
                people[index] = 0;
                count = 0;
                outCount++;
            }
        }
        index = (index + 1) % n;
    }

    int lastPerson;
    for (int i = 0; i < n; ++i) {
        if (people[i] != 0) {
            lastPerson = people[i];
            break;
        }
    }

    for (int i = 0; i < outOrder.size(); ++i) {
        cout << "No" << i + 1 << ": " << outOrder[i] << endl;
    }
    cout << "Last No is: " << lastPerson << endl;

    return 0;
}

R7-14 函数重载(数据类型不同)

用同一个函数名对n(n<=10)个数据进行从小到大排序,数据类型可以是整数、浮点数,用函数重载实现

输入格式:

输入n 例如 3
输入n个整数,例如 10 8 9
输入n个浮点数 例如 10.23 5.16 7.99

输出格式:

输出n个整数的升序排列:8 9 10
以空格间隔,并以空格结尾
换行,输出n个浮点数的升序排列:5.16 7.99 10.23
以空格间隔,并以空格结尾

输入样例:

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

3
10 8 9
10.23 5.16 7.89

输出样例:

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

8 9 10 
5.16 7.89 10.23 

AC: 

#include <iostream>
using namespace std;

// 对整数数组进行排序的函数
void order(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

// 对浮点数数组进行排序的函数
void order(double arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                double temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

// 输出数组元素的函数
template <typename T>
void print(T arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int n;
    cin >> n;

    // 处理整数数组
    int intArr[10];
    for (int i = 0; i < n; i++) {
        cin >> intArr[i];
    }
    order(intArr, n);
    print(intArr, n);

    // 处理浮点数数组
    double doubleArr[10];
    for (int i = 0; i < n; i++) {
        cin >> doubleArr[i];
    }
    order(doubleArr, n);
    print(doubleArr, n);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值