公式

B - 山寺の札 / Tags at the Mountain Temple 解説 by kyopro_friends


問題文の指示通りに入れ替え操作を行うことでこの問題を解くことができます。

多くの言語では配列の添字は \(0\) から始まることに注意してください。

実装例 (C++)

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

int main(){
  int n, q;
  cin >> n >> q;
  string s;
  cin >> s;

  for(int i=0; i<q; i++){
    int a, b;
    cin >> a >> b;
    a--, b--;
    swap(s[a], s[b]);
  }

  cout << s << endl;
}

python では文字列を直接変更することはできないため、文字のリストなどに変換してから操作を行います。

実装例 (Python)

N, Q = map(int, input().split())
S = list(input())

for _ in range(Q):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  S[a], S[b] = S[b], S[a]

print("".join(S))