[백준 10501] Ragged Right (C#, C++) - soo:bak
작성일 :
문제 링크
설명
문단의 각 줄 길이를 보고, 가장 긴 줄 길이를 n이라 할 때 마지막 줄을 제외한 각 줄에 대해 (n - 길이)²을 더한 값을 들쭉날쭉함 점수로 출력하는 문제입니다.
접근법
입력을 모두 읽어 줄 길이 배열을 만든 뒤, 최대 길이 n을 구합니다.
마지막 줄을 제외하고 각 길이에 대해 (n - len)²을 합산하여 출력합니다.
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
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var lines = new List<string>();
string? line;
while ((line = Console.ReadLine()) != null)
lines.Add(line);
if (lines.Count == 0) return;
int maxLen = 0;
foreach (var l in lines)
if (l.Length > maxLen) maxLen = l.Length;
long sum = 0;
for (int i = 0; i + 1 < lines.Count; i++) {
int diff = maxLen - lines[i].Length;
sum += 1L * diff * diff;
}
Console.WriteLine(sum);
}
}
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
28
29
30
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<string> vs;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vs lines;
string line;
while (getline(cin, line))
lines.push_back(line);
if (lines.empty()) return 0;
int maxLen = 0;
for (auto &s : lines)
maxLen = max(maxLen, (int)s.size());
ll sum = 0;
for (size_t i = 0; i + 1 < lines.size(); i++) {
ll diff = maxLen - (int)lines[i].size();
sum += diff * diff;
}
cout << sum << "\n";
return 0;
}