Submission
Status:
[PPPPPPPPPPPPPPPPPP]
Subtask/Task Score:
{100/100}
Score: 100
User: syndrxme
Problemset: การจัดแนวข้อความ
Language: cpp
Time: 0.002 second
Submitted On: 2026-03-14 10:57:19
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
// แนะนำตามโจทย์เพื่อความรวดเร็ว
cin.tie(nullptr)->sync_with_stdio(false); // [cite: 94]
int n, m;
if (!(cin >> n >> m)) return 0;
vector<string> words(n);
for (int i = 0; i < n; i++) {
cin >> words[i];
}
int i = 0;
while (i < n) {
int j = i;
int current_len = 0;
// 1. หาว่าบรรทัดนี้ใส่ได้กี่คำ
// (current_len + ความยาวคำถัดไป + จำนวนช่องว่างขั้นต่ำ j-i)
while (j < n && current_len + words[j].length() + (j - i) <= m) {
current_len += words[j].length();
j++;
}
int num_words = j - i;
int total_spaces = m - current_len;
// 2. กรณีบรรทัดสุดท้าย หรือ มีคำเดียวในบรรทัด
if (j == n || num_words == 1) { // [cite: 66, 69]
for (int k = i; k < j; k++) {
cout << words[k];
if (k < j - 1) {
cout << " ";
total_spaces--; // หักลบช่องว่างที่ใช้ไป
}
}
// เติมช่องว่างด้านหลังให้ครบ M
while (total_spaces > 0) {
cout << " ";
total_spaces--;
}
}
// 3. กรณีบรรทัดปกติ (มีพื้นที่เหลือและต้องกระจายช่องว่าง)
else { //
int gaps = num_words - 1;
int base_spaces = total_spaces / gaps;
int extra_spaces = total_spaces % gaps;
for (int k = i; k < j; k++) {
cout << words[k];
if (k < j - 1) {
// ช่องว่างที่จะเติม = ขั้นต่ำ + (ถ้ายังมีเศษเหลือให้บวก 1)
int spaces_to_add = base_spaces + (extra_spaces > 0 ? 1 : 0);
extra_spaces--;
for (int s = 0; s < spaces_to_add; s++) cout << " ";
}
}
}
cout << '\n'; // ขึ้นบรรทัดใหม่ด้วย '\n' ตามที่โจทย์แนะนำ [cite: 94]
i = j; // ขยับไปทำกลุ่มคำชุดต่อไป
}
return 0;
}