Submission

Status:

[PPPPPPPPPPPPPPPPPP]

Subtask/Task Score:

{100/100}

Score: 100

User: Gump2011

Problemset: การจัดแนวข้อความ

Language: cpp

Time: 0.003 second

Submitted On: 2026-03-08 18:17:52

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int N, M;
    cin >> N >> M;
    vector<string> words(N);
    for (int i = 0; i < N; i++) cin >> words[i];

    int i = 0;
    while (i < N) {
        int len = words[i].size();
        int j = i + 1;
        // หาคำที่จะใส่ในบรรทัดนี้
        while (j < N && len + 1 + words[j].size() <= M) {
            len += 1 + words[j].size();
            j++;
        }

        int num_words = j - i;
        int total_len = 0;
        for (int k = i; k < j; k++) total_len += words[k].size();

        string line;
        if (j == N || num_words == 1) {
            // บรรทัดสุดท้ายหรือมีคำเดียว: left justify
            line += words[i];
            for (int k = i + 1; k < j; k++) line += " " + words[k];
            // เติม space ให้ครบ M ถ้าเป็นบรรทัดเดียวหรือไม่ใช่บรรทัดสุดท้าย
            line += string(M - line.size(), ' ');
        } else {
            // จัด justify
            int spaces_needed = M - total_len;
            int space_between = spaces_needed / (num_words - 1);
            int extra = spaces_needed % (num_words - 1);
            for (int k = i; k < j; k++) {
                line += words[k];
                if (k < j - 1) {
                    int sp = space_between + (extra-- > 0 ? 1 : 0);
                    line += string(sp, ' ');
                }
            }
        }

        cout << line << '\n';
        i = j;
    }

    return 0;
}