交换元素使两个数组相同

In Berland each high school student is characterized byacademic performance — integer value between1 and 5.

In high school 0xFF there are two groups of pupils: the groupA and the group B. Each group consists of exactlyn students. An academic performance of each student is known — integer value between1 and 5.

The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to1, the same number of students whose academic performance is2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.

To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one s

# 题目重述 将两个整型数组 `a` 和 `b` 的**全部元素进行交换**,无论其长度是否相同。 输入包括数组 `a` 的长度 `n` 及其 `n` 个元素数组 `b` 的长度 `m` 及其 `m` 个元素交换后,`a` 数组的内容变为原来的 `b` 数组内容,`b` 数组的内容变为原来的 `a` 数组内容,并输出交换后的两个数组。 --- # 详解 本题核心是**交换两个数组的全部数据内容**,而不是逐位置对应交换(因为长度可能不同)。从测试用例来看: - 输入: - `n = 10` - `a = [91, 1, 42, 32, 9, 57, 6, 33, 2, 88]` - `m = 3` - `b = [52, 37, 19]` - 预期输出: ``` 52 37 19 91 1 42 32 9 57 6 33 2 88 ``` 说明: - 交换后,`a` 数组变成了原 `b` 的内容(3 个元素) - `b` 数组变成了原 `a` 的内容(10 个元素) 即:实现了**两个数组整体内容的互换**。 由于 C 语言不支持直接赋值数组,必须通过循环逐个复制元素。 ### 解决方案: 使用一个临时数组保存原 `a` 的内容,然后将 `b` 赋给 `a`,再将临时数组赋给 `b`。 ### ✅ 正确代码实现: ```c #include <stdio.h> int main() { int n, m; scanf("%d", &n); int a[100], b[100]; // 假设最大长度为100,足够容纳数据 int i; // 输入数组 a 的 n 个元素 for (i = 0; i < n; i++) { scanf("%d", &a[i]); } // 输入数组 b 的长度 m 及其 m 个元素 scanf("%d", &m); for (i = 0; i < m; i++) { scanf("%d", &b[i]); } /********** Begin **********/ // 创建临时数组保存原 a 的内容 int temp[100]; // 1. 保存原 a for (i = 0; i < n; i++) { temp[i] = a[i]; } // 2. 将 b 的内容复制到 a for (i = 0; i < m; i++) { a[i] = b[i]; } // 3. 将原 a 的内容复制回 b for (i = 0; i < n; i++) { b[i] = temp[i]; } /********** End **********/ // 输出交换后的 a(现在是原 b 的值) for (i = 0; i < m; i++) { printf("%d ", a[i]); } printf("\n"); // 输出交换后的 b(现在是原 a 的值) for (i = 0; i < n; i++) { printf("%d ", b[i]); } printf("\n"); return 0; } ``` --- ### 执行流程验证: 输入: ``` 10 91 1 42 32 9 57 6 33 2 88 3 52 37 19 ``` 内存变化: - 初始: - `a = [91, 1, 42, 32, 9, 57, 6, 33, 2, 88]` - `b = [52, 37, 19]` - 执行交换: - `temp = [91, 1, ..., 88]`(保存原 `a`) - `a = [52, 37, 19]`(从 `b` 复制) - `b = [91, 1, ..., 88]`(从 `temp` 复制) 输出: ``` 52 37 19 91 1 42 32 9 57 6 33 2 88 ``` ✅ 完全符合预期。 --- # 知识点 1. **数组内容交换机制** 使用临时数组缓存一方数据,防止在交换过程中原始数据丢失。 2. **变长数组复制** 复制时需根据各自长度独立控制循环次数,避免越界或遗漏。 3. **输入输出动态匹配** 输出元素个数应与交换数组的实际长度一致,不能硬编码。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值