The first line gives n and the second line a list of n integers. The third line gives the number of commands q, and each of the next q lines gives "l r" (1 ≤ l ≤ r ≤ n, positions counted from 1). For each command, reverse the items from position l to position r in place. Apply the commands in the given order, each to the list as left by the previous ones. Print the final list on one line, separated by single spaces. Try solving it with a function that takes the list and a range and reverses it, using a function that swaps two items.
Input
1 ≤ n ≤ 1,000, 1 ≤ q ≤ 1,000, every value is an integer from -1,000,000,000 to 1,000,000,000
Output
One line: the final list
Example 1 · stdin
5
1 2 3 4 5
2
1 3
3 5
stdout
3 2 5 4 1
main.py
Error List00F8 ↓ · ⇧F8 ↑
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
Swap the two ends and move inward one step at a time, swapping only while l < r. Going all the way (i <= r) passes the middle and swaps everything back. Swapping two items: Python a[i], a[j] = a[j], a[i], JavaScript/TypeScript [a[i], a[j]] = [a[j], a[i]], C++ std::swap(a[i], a[j]), C# (a[i], a[j]) = (a[j], a[i]), and in Java, C and Craykon a temporary t. Passing to a function is the key point. A plain number parameter is a copy in every language, so Python def swap(x, y): x, y = y, x or C void swap(int x, int y) only swaps the copies inside the function and the list stays the same. A list is passed as the same list in Python, JavaScript, TypeScript, Java, C# and Craykon (the reference is copied), so changing its items inside the function changes them outside too; pass the list and the indices. C can pass addresses with void swap(int *x, int *y), and C# can pass the variable itself with ref int x. Careful in C++: void f(std::vector<int> a) receives a full copy of the vector, so changes do not reach the caller; take std::vector<int>& a (a reference).
Pythonmain.py · 15 lines
def reverse_range(a, l, r): """a[l..r](0부터)를 제자리에서 뒤집는다. 목록은 함수 밖의 것과 같은 것이다.""" while l < r: a[l], a[r] = a[r], a[l] l += 1 r -= 1n = int(input())a = list(map(int, input().split()))q = int(input())for _ in range(q): l, r = map(int, input().split()) reverse_range(a, l - 1, r - 1)print(*a)
JavaScriptmain.js · 16 lines
const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// 배열은 같은 것이 넘어오므로 함수 안에서 바꾸면 밖에서도 바뀐다function reverseRange(a, l, r) { while (l < r) { [a[l], a[r]] = [a[r], a[l]]; l++; r--; }}const n = nums[0];const a = nums.slice(1, 1 + n);const q = nums[1 + n];for (let k = 0; k < q; k++) reverseRange(a, nums[2 + n + 2 * k] - 1, nums[3 + n + 2 * k] - 1);console.log(a.join(" "));
TypeScriptmain.ts · 17 lines
import { readFileSync } from "node:fs";const nums: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// 배열은 같은 것이 넘어오므로 함수 안에서 바꾸면 밖에서도 바뀐다function reverseRange(a: number[], l: number, r: number): void { while (l < r) { [a[l], a[r]] = [a[r], a[l]]; l++; r--; }}const n: number = nums[0];const a: number[] = nums.slice(1, 1 + n);const q: number = nums[1 + n];for (let k = 0; k < q; k++) reverseRange(a, nums[2 + n + 2 * k] - 1, nums[3 + n + 2 * k] - 1);console.log(a.join(" "));
JavaMain.java · 31 lines
import java.util.Scanner;import java.util.StringJoiner;public class Main { // 배열은 참조가 복사되어 넘어오므로 칸을 바꾸면 밖의 배열이 바뀐다 static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } static void reverseRange(int[] a, int l, int r) { while (l < r) swap(a, l++, r--); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); int q = sc.nextInt(); for (int k = 0; k < q; k++) { int l = sc.nextInt(); int r = sc.nextInt(); reverseRange(a, l - 1, r - 1); } StringJoiner out = new StringJoiner(" "); for (int v : a) out.add(String.valueOf(v)); System.out.println(out); }}
C#Main.cs · 29 lines
using System;using System.Linq;class Program{ // ref로 받으면 넘긴 변수 자체를 바꾼다(a[i], a[j] 칸을 직접) static void Swap(ref int x, ref int y) { (x, y) = (y, x); } static void ReverseRange(int[] a, int l, int r) { while (l < r) Swap(ref a[l++], ref a[r--]); } static void Main() { Console.ReadLine(); int[] a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); int q = int.Parse(Console.ReadLine()); for (int k = 0; k < q; k++) { int[] lr = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); ReverseRange(a, lr[0] - 1, lr[1] - 1); } Console.WriteLine(string.Join(" ", a)); }}
C++main.cpp · 22 lines
#include <iostream>#include <utility>#include <vector>// vector를 &(참조)로 받아야 밖의 것이 바뀐다. 그냥 받으면 복사본만 바뀐다void reverse_range(std::vector<int>& a, int l, int r) { while (l < r) std::swap(a[l++], a[r--]);}int main() { int n, q, l, r; std::cin >> n; std::vector<int> a(n); for (int& v : a) std::cin >> v; std::cin >> q; for (int k = 0; k < q; k++) { std::cin >> l >> r; reverse_range(a, l - 1, r - 1); } for (int i = 0; i < n; i++) std::cout << (i ? " " : "") << a[i]; std::cout << "\n";}
Cmain.c · 26 lines
#include <stdio.h>/* 값이 아니라 주소를 받아야 넘긴 칸이 바뀐다 */void swap(int *x, int *y) { int t = *x; *x = *y; *y = t;}void reverse_range(int *a, int l, int r) { while (l < r) swap(&a[l++], &a[r--]);}int main(void) { int n, q, l, r, a[1000]; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); scanf("%d", &q); for (int k = 0; k < q; k++) { scanf("%d %d", &l, &r); reverse_range(a, l - 1, r - 1); } for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]); putchar('\n'); return 0;}
Craykonmain.cray · 27 lines
// 목록은 같은 것이 넘어오므로 함수 안에서 칸을 바꾸면 밖에서도 바뀐다자리바꾸기(목록, i, j){ t = 목록[i]; 목록[i] = 목록[j]; 목록[j] = t;}구간뒤집기(목록, l, r){ while (l < r) { 자리바꾸기(목록, l, r); l += 1; r -= 1; }}n = Console.ReadLine().ToNumber();a = Console.ReadNumbers();q = Console.ReadLine().ToNumber();for (k = 0; k < q; k++){ lr = Console.ReadNumbers(); 구간뒤집기(a, lr[0] - 1, lr[1] - 1);}Console.WriteLine(a);