해달
2020. 1. 15. 08:00
문제
2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
출력
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
코드
#include <iostream> #include <bitset> using namespace std; bitset<1024> Numbers; int N, K; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> N >> K; for (int i = 2; i <= N; ++i) { if (Numbers[j]) continue; for (int j = i; j <= N; j += i) { if (Numbers[j] == false) { Numbers[j] = true; --K; if (K == 0) { cout << j; return 0; } } } } } |
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace ForAlgoCsharp { class Program { class Point : IComparable<Point> { public int x = 0; public int y = 0; public Point(string input) { string[] inputs = input.Split(); x = Convert.ToInt32(inputs[0]); y = Convert.ToInt32(inputs[1]); } public int CompareTo(Point other) { if (x == other.x) return y.CompareTo(other.y); return x.CompareTo(other.x); } public void PrintTo(StringBuilder sb) { sb.Append($"{x} {y}").AppendLine(); } } static List<Point> list = new List<Point>(100000); static int N; static void Main(string[] args) { N = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < N; ++i) { string line = Console.ReadLine(); Point p = new Point(line); list.Add(p); } list.Sort(0, N, Comparer<Point>.Default); StringBuilder sb = new StringBuilder(); for (int i = 0; i < N; ++i) { list[i].PrintTo(sb); } Console.Write(sb); } } } |
from sys import stdin, stdout input() stdout.write( '\n'.join( f'{x} {y}' for x, y in sorted( tuple(map(int, line.split())) for line in stdin ) ) ) |
복기
C#에서 입력 받을 때는 Convert 클래스를 사용하고 출력할 때는 StringBuilder 클래스를 사용하자. Python에서 문자열 병합(string concatenation)에는 다음과 같은 방법이 있다.