Files
python/TangDou/AcWing/IDAstar/180_Prepare_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

49 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
void print() {
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
}
int main() {
// 将数组中一段234位置与56互换
// 学习一下常见的移动元素的策略,实现了将序列右移的目的。
int st = 1; // 开始下标
int ed = 5; // 结束下标 len=(ed-st+1),共(5-1+1)=5个
int len = 3; // 前半段串的长度
//(1)将234反转
reverse(a + st, a + st + len); // 参数:开始的数组索引,开始数组索引+要翻转的长度,这是一个前闭后开的区间[)
print();
//(2)将56反转
reverse(a + st + len, a + ed + 1); // 时刻注意前闭后开
print();
//(3)将23456反转
reverse(a + st, a + ed + 1); // 整个区间翻转,就实现了两个子串互换位置的目标
print();
// 输出:1 5 6 2 3 4 7 8 9 10
// 与预期结果一致
puts("");
// 尝试再反转回来
// 后串长度:
reverse(a + st, a + ed + 1 - len);
print();
reverse(a + ed - len + 1, a + ed + 1);
print();
reverse(a + st, a + ed + 1);
print();
// 输出:1 2 3 4 5 6 7 8 9 10
// 与预期结果一致
return 0;
}