{ }codelper
swapping valuesreading n linesP0046

Swap the cards

n cards lie in a row, at positions 1, 2, …, n from the left.
The first line gives n and the number of swaps m, and the second line gives the n numbers written on the cards, from the left.
Each of the next m lines gives two positions i and j.
In the given order, swap the card at position i with the card at position j (if i equals j nothing happens).
After all swaps, print the numbers on the cards from the left on one line, separated by single spaces.

Input
1 ≤ n ≤ 1,000, 1 ≤ m ≤ 1,000, 1 ≤ card number ≤ 1,000,000,000, 1 ≤ i, j ≤ n
Output
the n card numbers on one line
Example 1 · stdin
4 3
10 20 30 40
1 4
2 3
1 2
stdout
30 40 20 10
Example 2 · stdin
3 3
3 3 8
1 2
2 2
3 1
stdout
8 3 3
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Languages split into those with a one-line swap and those without.
Python a[i], a[j] = a[j], a[i] (the right-hand tuple is built first, then unpacked), JS/TS [a[i], a[j]] = [a[j], a[i]] (destructuring — if the previous line has no ;, x\n[a[i], …] is read as x[…], so be careful), C# (a[i], a[j]) = (a[j], a[i]) (tuples, since C# 7), C++ std::swap(a[i], a[j]).
Java, C and Craykon have no such syntax, so use a temporary: tmp = a[i]; a[i] = a[j]; a[j] = tmp;.
The most common trap is writing a[i] = a[j]; a[j] = a[i]; without a temporary — the first line wipes out the old a[i], so both slots end up equal.
The second is moving the swap into a function: Java swap(int x, int y) and C swap(int x, int y) receive copies of the values, so the array does not change.
C needs pointers, swap(int *x, int *y), Java must pass the array and two indices, and C++ takes references int&, which is how std::swap works.
The third is the XOR trick x ^= y; y ^= x; x ^= y;: when i and j are the same slot it XORs the value with itself and leaves 0 — example 2 has a line that swaps a position with itself.

Pythonmain.py · 7 lines
n, m = map(int, input().split())cards = list(map(int, input().split()))for _ in range(m):    i, j = map(int, input().split())    # 오른쪽이 먼저 다 계산된 뒤 왼쪽에 담기므로 임시 변수가 필요 없다    cards[i - 1], cards[j - 1] = cards[j - 1], cards[i - 1]print(*cards)
JavaScriptmain.js · 9 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const [n, m] = lines[0].trim().split(/\s+/).map(Number);const cards = lines[1].trim().split(/\s+/).map(Number);for (let k = 0; k < m; k++) {  const [i, j] = lines[2 + k].trim().split(/\s+/).map((s) => Number(s) - 1);  // 구조 분해 대입: 오른쪽 배열을 먼저 만든 뒤 나눠 담는다  [cards[i], cards[j]] = [cards[j], cards[i]];}console.log(cards.join(" "));
TypeScriptmain.ts · 10 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const [n, m]: number[] = lines[0].trim().split(/\s+/).map(Number);const cards: number[] = lines[1].trim().split(/\s+/).map(Number);for (let k = 0; k < m; k++) {  const [i, j]: number[] = lines[2 + k].trim().split(/\s+/).map((s) => Number(s) - 1);  // 구조 분해 대입: 오른쪽 배열을 먼저 만든 뒤 나눠 담는다  [cards[i], cards[j]] = [cards[j], cards[i]];}console.log(cards.join(" "));
JavaMain.java · 31 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer st = new StringTokenizer(in.readLine());        int n = Integer.parseInt(st.nextToken());        int m = Integer.parseInt(st.nextToken());        int[] cards = new int[n];        st = new StringTokenizer(in.readLine());        for (int k = 0; k < n; k++) cards[k] = Integer.parseInt(st.nextToken());        for (int k = 0; k < m; k++) {            st = new StringTokenizer(in.readLine());            int i = Integer.parseInt(st.nextToken()) - 1;            int j = Integer.parseInt(st.nextToken()) - 1;            // Java에는 한 줄 바꾸기가 없어 임시 변수를 쓴다            int tmp = cards[i];            cards[i] = cards[j];            cards[j] = tmp;        }        StringBuilder out = new StringBuilder();        for (int k = 0; k < n; k++) {            if (k > 0) out.append(' ');            out.append(cards[k]);        }        System.out.println(out);    }}
C#Main.cs · 19 lines
using System;using System.Linq; class Program{    static void Main()    {        int m = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray()[1];        int[] cards = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();        for (int k = 0; k < m; k++)        {            int[] ij = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();            int i = ij[0] - 1, j = ij[1] - 1;            // 튜플로 한 번에 바꾼다(C# 7부터)            (cards[i], cards[j]) = (cards[j], cards[i]);        }        Console.WriteLine(string.Join(" ", cards));    }}
C++main.cpp · 17 lines
#include <iostream>#include <utility>#include <vector> int main() {    int n, m;    std::cin >> n >> m;    std::vector<int> cards(n);    for (int& c : cards) std::cin >> c;    for (int k = 0; k < m; k++) {        int i, j;        std::cin >> i >> j;        std::swap(cards[i - 1], cards[j - 1]);  // 참조로 받아 바꾼다    }    for (int k = 0; k < n; k++) std::cout << (k ? " " : "") << cards[k];    std::cout << '\n';}
Cmain.c · 19 lines
#include <stdio.h> int main(void) {    int n, m;    static int cards[1000];    scanf("%d %d", &n, &m);    for (int k = 0; k < n; k++) scanf("%d", &cards[k]);    for (int k = 0; k < m; k++) {        int i, j;        scanf("%d %d", &i, &j);        /* 임시 변수에 한쪽을 먼저 맡겨 둔다 */        int tmp = cards[i - 1];        cards[i - 1] = cards[j - 1];        cards[j - 1] = tmp;    }    for (int k = 0; k < n; k++) printf(k ? " %d" : "%d", cards[k]);    printf("\n");    return 0;}
Craykonmain.cray · 14 lines
첫줄 = Console.ReadNumbers();m = 첫줄[1];카드 = Console.ReadNumbers();for (k = 0; k < m; k++){    자리 = Console.ReadNumbers();    i = 자리[0] - 1;    j = 자리[1] - 1;    // 한쪽을 먼저 임시로 맡겨 둔다    임시 = 카드[i];    카드[i] = 카드[j];    카드[j] = 임시;}Console.WriteLine(카드);