C# 코테용 정리

기본적으로 using에 추가해 두면 좋은 라이브러리

using System;
using System.IO;            // StreamReader/Writer → 빠른 입출력
using System.Text;          // StringBuilder, Encoding
using System.Collections;   // 기본 컬렉션
using System.Collections.Generic; // List, Dictionary, HashSet, Queue, Stack
using System.Linq;          // LINQ 쿼리 (정렬/검색/집계)
  • System.Numerics → BigInteger (큰 수 계산 필요 시)
  • System.Diagnostics → Stopwatch (시간 측정용)

코테에서 자주 쓰이는 자료형

  • 배열 (int[]) → 기본
  • List → 가변 크기 배열, 정렬(Sort), 탐색(BinarySearch)
  • Dictionary<K,V> → key-value 매핑
  • HashSet → 중복 제거, O(1) 포함 여부 체크
  • Queue → BFS (너비 우선 탐색)
  • Stack → DFS, 괄호 검증 등
  • PriorityQueue<T,TPriority> (C# 9.0~, .NET 6 이상) → 다익스트라, 최소힙
  • Tuple / ValueTuple → (x, y) 좌표, 임시 페어 저장
  • StringBuilder → 문자열 합치기 시 필수 (O(1) Append)

시간 단축용 메서드/기능

  • 입출력
    • Console.ReadLine() → 기본 입력
    • StreamReader, StreamWriter → 대량 입출력
    • StringBuilder + AppendLine → 대량 출력
  • 문자열 파싱
    • Split() → 공백 구분 입력
    • int.Parse, long.Parse, double.Parse
    • string.Join(" ", list) → 출력 포맷팅
  • 컬렉션 관련
    • List.Sort() / Array.Sort() → O(N log N)
    • list.BinarySearch(x) → O(log N)
    • dict.ContainsKey(key), hash.Contains(val) → O(1)
    • queue.Enqueue(x), queue.Dequeue()
    • stack.Push(x), stack.Pop()
  • LINQ (빠르게 집계할 때 유용)
    • arr.Min(), arr.Max()
    • arr.Sum(), arr.Average()
    • arr.OrderBy(x => x)
    • 단, 성능 critical 문제에서는 반복문으로 대체 권장.

예문

입출력

// 기본 입력
string line = Console.ReadLine();

// 대량 입력
using var sr = new StreamReader(Console.OpenStandardInput());
using var sw = new StreamWriter(Console.OpenStandardOutput());
string input = sr.ReadLine();
sw.WriteLine("출력 예시");

// StringBuilder 출력 누적
var sb = new StringBuilder();
sb.AppendLine("첫 줄");
sb.AppendLine("둘째 줄");
Console.Write(sb.ToString());

문자열 파싱

// 공백 단위로 쪼개기
string[] parts = Console.ReadLine().Split();
int a = int.Parse(parts[0]);
int b = int.Parse(parts[1]);

// 여러 개 숫자 변환
int[] arr = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

// 출력 합치기
int[] nums = { 1, 2, 3, 4 };
string joined = string.Join(" ", nums);  // "1 2 3 4"

컬렉션 관련

// 정렬
int[] arr = { 5, 1, 3, 2, 4 };
Array.Sort(arr);          // [1,2,3,4,5]
var list = new List<int>{ 5, 1, 3 };
list.Sort();              // [1,3,5]

// 이진 탐색
int idx = Array.BinarySearch(arr, 3);   // 값 3의 인덱스 반환

// Dictionary
var dict = new Dictionary<string, int>();
dict["apple"] = 5;
if (dict.ContainsKey("apple")) Console.WriteLine(dict["apple"]);

// HashSet
var set = new HashSet<int>{ 1, 2, 3 };
Console.WriteLine(set.Contains(2));  // true

Queue / Stack

// Queue
var q = new Queue<int>();
q.Enqueue(10);
q.Enqueue(20);
Console.WriteLine(q.Dequeue());  // 10

// Stack
var st = new Stack<string>();
st.Push("A");
st.Push("B");
Console.WriteLine(st.Pop());  // "B"

우선순위 큐 (C# 9.0+, .NET 6~)

// 최소힙 형태
var pq = new PriorityQueue<int, int>();
pq.Enqueue(5, 5);
pq.Enqueue(1, 1);
pq.Enqueue(3, 3);

Console.WriteLine(pq.Dequeue());  // 1

LINQ

int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(arr.Min());   // 1
Console.WriteLine(arr.Max());   // 5
Console.WriteLine(arr.Sum());   // 15
Console.WriteLine(arr.Average()); // 3
var sorted = arr.OrderByDescending(x => x).ToArray(); // [5,4,3,2,1]

필수 분야 / 스킬

  1. 자료구조
    • 스택, 큐, 덱
    • 힙 (우선순위 큐)
    • 트리/그래프 (DFS, BFS, Union-Find)
    • HashMap/Set 응용
  2. 알고리즘
    • 정렬: O(N log N) 정렬, Counting Sort 개념
    • 탐색: 이진 탐색, 투 포인터, 슬라이딩 윈도우
    • 그래프: BFS, DFS, 다익스트라, 플로이드, 벨만-포드
    • DP: LIS, 배낭 문제, 이항 계수, 메모이제이션
    • 그리디: 정렬 + 선택
    • 문자열: KMP, Rabin-Karp, Trie 기본
  3. 수학 / 구현
    • GCD/LCM (Math or 직접 구현)
    • 소수 판별, 에라토스테네스의 체
    • 조합/순열 (팩토리얼, 모듈러 연산)
    • 좌표계 시뮬레이션 (상하좌우)
  4. 최적화
    • 빠른 입출력 습관화
    • StringBuilder 적극 활용
    • HashSet/Dictionary로 O(1) 탐색
    • 재귀 → 스택오버플로우 위험 → 반복/스택으로 치환 고려

추천 학습 루트

  1. 입출력 최적화 + 기본 자료구조 (배열, List, Dictionary, HashSet, Queue, Stack)
  2. 정렬/탐색 문제 (이진 탐색, 투 포인터, 슬라이딩 윈도우)
  3. 그래프 탐색 (DFS, BFS, 다익스트라)
  4. DP (대표 문제: 계단 오르기, LIS, 배낭 문제)
  5. 문자열 알고리즘 (KMP, Trie 기본)
  6. 수학/조합론 (에라토스테네스, 모듈러 연산, 이항계수)

정리

  • 기본 using + 자료형 세트를 미리 고정해두고,
  • 빠른 입출력 + StringBuilder 습관,
  • 자주 쓰이는 알고리즘 패턴(BFS/DFS, DP, 투포인터) 숙지.