欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

AOJ (C++ Programming II)—4-C-swap

程序员文章站 2022-04-14 11:19:43
4-C-swap题目Swap Write a program which reads a sequence of integers A={a0,a1,…,an−1} and swap specified elements by a list of the following operation: swapRange(b,e,t): For each integer k (0≤k<(e−b), swap element (b+k) and element (t+k).输入The input is...

4-C-swap

题目

Swap Write a program which reads a sequence of integers A={a0,a1,…,an−1} and swap specified elements by a list of the following operation: swapRange(b,e,t): For each integer k (0≤k<(e−b), swap element (b+k) and element (t+k).
输入
The input is given in the following format.
n
a0 a1…,an−1
q
b1 e1 t1
b2 e2 t2
:
bq eq tq
In the first line, n (the number of elements in A) is given. In the second line, ai (each element in A) are given. In the third line, the number of queries q is given and each query is given by three integers bi ei ti in the following q lines.
输出
Print all elements of A in a line after performing the given operations. Put a single space character between adjacency elements and a newline at the end of the last element.
样例输入
11
1 2 3 4 5 6 7 8 9 10 11
1
1 4 7
样例输出
1 8 9 10 5 6 7 2 3 4 11
提示:swap_ranges(A.begin() + b, A.begin()+m,A.begin() + e);

题解(代码流程)

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n, q;
    cin >> n;
    vector<int> A(n);
    for (int i = 0; i < n; i++)cin >> A[i];
    cin >> q;
    while (q--) {
        int b, e, t;
        cin >> b >> t >> e;
        swap_ranges(A.begin() + b, A.begin() + t, A.begin() + e);//调用swap_ranges函数,代入三个迭代器参数
    }
    for (auto e:A) {
        cout << e << " ";
    }
    cout << endl;
    return 0;
}

小结

学会运用swap_ranges函数来交换范围中的元素

swap_ranges()

本文地址:https://blog.csdn.net/m0_45695811/article/details/107961266