풀지 않고 압축된 채로
사전순 비교하기
단어 길이 ≤ 100 · 숫자 1 ~ 109
메모리도 시간도 감당할 수 없다
숫자를 글자로 비교하면 순서가 틀어진다
개수가 적은 쪽이 앞인지 뒤인지는 다음 글자에 달려 있다
1def parse(s):2 runs = []3 i = 04 while i < len(s):5 j = i + 16 while j < len(s) and s[j].isdigit():7 j += 18 runs.append([s[i], int(s[i + 1:j])])9 i = j10 return runs
s[i]: 글자j: 숫자가 끝나는 다음 위치s[i + 1:j]: 숫자 부분 → int1def compare(a, b):2 i = j = 03 ra, rb = a[0][1], b[0][1]4 while i < len(a) and j < len(b):5 if a[i][0] != b[j][0]:6 return -1 if a[i][0] < b[j][0] else 17 m = min(ra, rb)8 ra -= m9 rb -= m10 if ra == 0:11 i += 112 ra = a[i][1] if i < len(a) else 013 if rb == 0:14 j += 115 rb = b[j][1] if j < len(b) else 016 if i == len(a) and j == len(b):17 return 018 return -1 if i == len(a) else 1
1order = sorted(range(n), key=cmp_to_key(2 lambda x, y: compare(runs[x], runs[y])))
cmp_to_key: 비교 함수를 정렬 기준으로 (functools)| 풀이 | 무엇이 문제인가 | 통과 |
|---|---|---|
| 풀어서 비교 | 최대 500억 글자 → 메모리·시간 초과 | 10 / 20 |
| 압축 문자열 그대로 정렬 | "a10" < "a9" | 4 / 20 |
| (글자, 개수) 묶음끼리 비교 | a2b1 < a3으로 판정 | 6 / 20 |
| C++ sort 사용 | 안정 정렬이 아님 → 같은 단어 순서가 바뀜 | 14 / 20 |
| 모범 답안 | 정답 | 20 / 20 |
1import sys2from functools import cmp_to_key3input = sys.stdin.readline45def parse(s):6 """'a3b12' → [['a', 3], ['b', 12]]"""7 runs = []8 i = 09 while i < len(s):10 j = i + 111 while j < len(s) and s[j].isdigit():12 j += 1 # 숫자가 끝나는 곳 찾기13 runs.append([s[i], int(s[i + 1:j])])14 i = j15 return runs1617def compare(a, b):18 """풀었을 때 a가 앞이면 -1, 같으면 0, 뒤면 1"""19 i = j = 020 ra, rb = a[0][1], b[0][1] # 지금 묶음에 남은 글자 수21 while i < len(a) and j < len(b):22 if a[i][0] != b[j][0]:23 return -1 if a[i][0] < b[j][0] else 124 m = min(ra, rb) # 같은 글자가 겹치는 만큼 건너뛴다25 ra -= m26 rb -= m27 if ra == 0: # a의 묶음을 다 썼다28 i += 129 ra = a[i][1] if i < len(a) else 030 if rb == 0: # b의 묶음을 다 썼다31 j += 132 rb = b[j][1] if j < len(b) else 033 if i == len(a) and j == len(b):34 return 035 return -1 if i == len(a) else 1 # 먼저 끝난 쪽이 앞3637n = int(input())38words = [input().strip() for _ in range(n)]39runs = [parse(w) for w in words]40order = sorted(range(n), key=cmp_to_key(lambda x, y: compare(runs[x], runs[y])))41for i in order:42 print(words[i])
1#include <bits/stdc++.h>2using namespace std;34typedef vector<pair<char, long long>> Runs; // (글자, 개수) 묶음56Runs parse(const string& s) {7 Runs r;8 size_t i = 0;9 while (i < s.size()) {10 char ch = s[i++];11 long long cnt = 0;12 while (i < s.size() && isdigit(s[i]))13 cnt = cnt * 10 + (s[i++] - '0');14 r.push_back({ch, cnt});15 }16 return r;17}1819int compare(const Runs& a, const Runs& b) {20 size_t i = 0, j = 0;21 long long ra = a[0].second, rb = b[0].second;22 while (i < a.size() && j < b.size()) {23 if (a[i].first != b[j].first)24 return a[i].first < b[j].first ? -1 : 1;25 long long m = min(ra, rb); // 겹치는 만큼 건너뛴다26 ra -= m;27 rb -= m;28 if (ra == 0 && ++i < a.size()) ra = a[i].second;29 if (rb == 0 && ++j < b.size()) rb = b[j].second;30 }31 if (i == a.size() && j == b.size()) return 0;32 return i == a.size() ? -1 : 1; // 먼저 끝난 쪽이 앞33}3435int main() {36 int n;37 cin >> n;38 vector<string> w(n);39 vector<Runs> r(n);40 vector<int> order(n);41 for (int i = 0; i < n; i++) {42 cin >> w[i];43 r[i] = parse(w[i]);44 order[i] = i;45 }46 stable_sort(order.begin(), order.end(), [&](int x, int y) {47 return compare(r[x], r[y]) < 0; // 같으면 번호 순서 유지48 });49 for (int i : order) cout << w[i] << '\n';50}
isdigit로 숫자 끝 찾기단어 압축