0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AtCoder Beginner Contest 350 C問題

Posted at

AtCoder Beginner Contest 350 C問題
こちらの問題です。

問題

image.png

入出力例

image.png

解法

各要素A[i]をi+1にするために、A[i]とA[A[i] - 1]を交換します。
operationsに交換した操作を記録します。

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

int main() {
    int N;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; i++) {
        cin >> A[i];
    }

    vector<pair<int, int>> operations;

    for (int i = 0; i < N; i++) {
        while (A[i] != i + 1) {
            int swapWith = A[i] - 1;
            operations.push_back({i + 1, swapWith + 1});
            swap(A[i], A[swapWith]);
        }
    }

    cout << operations.size() << endl;
    for (auto op : operations) {
        cout << op.first << " " << op.second << endl;
    }

    return 0;
}


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?