[백준 29641] Текст (C#, C++) - soo:bak
작성일 :
문제 링크
설명
텍스트를 단어 단위로 나누어 각 줄의 길이가 k 이하가 되게 출력하되, 줄 수가 최소가 되도록 만드는 문제입니다.
접근법
왼쪽부터 단어를 한 줄에 가능한 만큼 채우는 그리디가 최적입니다.
현재 줄 길이에 단어와 공백 1칸을 더했을 때 k를 넘으면 줄을 바꾸고, 아니면 같은 줄에 붙입니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Text;
class Program {
static void Main() {
var parts = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
var idx = 0;
var k = int.Parse(parts[idx++]);
var outSb = new StringBuilder();
var line = "";
for (; idx < parts.Length; idx++) {
var w = parts[idx];
if (line.Length == 0) line = w;
else if (line.Length + 1 + w.Length <= k) line += " " + w;
else {
outSb.AppendLine(line);
line = w;
}
}
if (line.Length > 0) outSb.AppendLine(line);
Console.Write(outSb);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int k; cin >> k;
string word, line;
while (cin >> word) {
if (line.empty()) line = word;
else if ((int)line.size() + 1 + (int)word.size() <= k) {
line.push_back(' ');
line += word;
} else {
cout << line << "\n";
line = word;
}
}
if (!line.empty()) cout << line << "\n";
return 0;
}