Submission

Status:
[PPPPPPPPPPPPPPPPPP]

Score: 100

User: admin

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

Language: cpp

Time: 0.004 second

Submitted On: 2025-03-25 14:34:30

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

vector<string> fullJustify(vector<string>& words, int maxWidth) {
    vector<string> res;
    vector<string> line;
    int len = 0, i = 0;

    while (i < words.size()) {
        if (len + line.size() + words[i].size() > maxWidth) {
            int extra_spaces = maxWidth - len;
            int spaces = line.size() == 1 ? extra_spaces : extra_spaces / (line.size() - 1);
            int rem = line.size() == 1 ? 0 : extra_spaces % (line.size() - 1);

            string justified;
            for (int j = 0; j < line.size(); j++) {
                justified += line[j];
                if (j < line.size() - 1 || line.size() == 1) {
                    justified.append(spaces + (rem-- > 0 ? 1 : 0), ' ');
                }
            }

            res.push_back(justified);
            line.clear();
            len = 0;
        }

        line.push_back(words[i]);
        len += words[i].size();
        i++;
    }

    string lastline;
    for (int j = 0; j < line.size(); j++) {
        if (j > 0) lastline += ' ';
        lastline += line[j];
    }
    lastline.append(maxWidth - lastline.size(), ' ');
    res.push_back(lastline);

    return res;   
}

int N, M;
int main() {
	cin >> N >> M;
	
	vector<string> W;
	for (int i=0; i<N; i++) {
		string x;
		cin >> x;
		W.push_back(x);
	}
	auto r = fullJustify(W, M);
	for (auto i: r) {
		cout << i << '\n';
	}
}