Skip to content

USACO 2020 January Contest Bronze Division - Word Processor#

Problem link: here

Solution Author: Stefan Dascalescu

Problem Solution#

Just simulate the process and keep track of the final count.

Source codes#

The source codes in C++ and Python can be seen below.

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

int main()
{
    ifstream cin("word.in");
    ofstream cout("word.out");

    int n, k;
    cin >> n >> k;

    int cnt = 0;
    for(int i = 1; i <= n; i++)
    {
        string s;
        cin >> s;
        if(cnt + s.size() > k)
            cout << '\n', cnt = 0;
        else
            if(cnt != 0)
                cout << " ";
        cout << s;
        cnt += s.size();
    }

    return 0;
}
with open("word.in", "r") as fin:
    tokens = fin.read().split()
n = int(tokens[0])
k = int(tokens[1])
words = tokens[2:]
cnt = 0
line = ""
result = []
for s in words:
    if cnt + len(s) > k:
        result.append(line)
        line = s
        cnt = len(s)
    else:
        if cnt != 0:
            line += " " + s
        else:
            line = s
        cnt += len(s)
result.append(line)
with open("word.out", "w") as fout:
    fout.write("\n".join(result))