Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace PrettyPrinting
- {
- class Program
- {
- static void Main(string[] args)
- {
- string[] modusAndLineWidth = (Console.ReadLine()).Split(' ');
- int lineWidth = int.Parse(modusAndLineWidth[0]);
- int modus = int.Parse(modusAndLineWidth[1]);
- string[] text = (Console.ReadLine()).Split(' ');
- PrettyPrinting(text, lineWidth, modus);
- }
- static void PrettyPrinting(string[] text, int lineWidth, int modus)
- {
- int[][] ugliness = new int[text.Length][];
- for (int i = 0; i < text.Length; i++)
- {
- ugliness[i] = new int[lineWidth];
- //Compute the ugliness of multiple words after each other.
- for (int j = 0; j < lineWidth && i + j < text.Length; j++)
- {
- //The index of last word of the line in the text array
- int jInTextArray = i + j;
- if (j == 0)
- {
- //The ugliness of one word is the maximum line width minus the length of that word.
- ugliness[i][j] = lineWidth - text[i].Length;
- }
- //If there is a word with a '.' , '! 'or '?' than the uggliness of that line is set to 0
- else if (text[jInTextArray][text[jInTextArray].Length - 1] == '.' || text[jInTextArray][text[jInTextArray].Length - 1] == '!' ||
- text[jInTextArray][text[jInTextArray].Length - 1] == '?')
- {
- ugliness[i][j] = 0;
- }
- else
- {
- ugliness[i][j] = (ugliness[i][j - 1] - 1 - text[jInTextArray].Length) * (ugliness[i][j - 1] - 1 - text[jInTextArray].Length);
- }
- }
- }
- int[] totalUgliness = new int[text.Length];
- int[] resultIndices = new int[text.Length];
- //Compute the totalUgliness and the resultIndices bottum-up,
- //this also means that the total ugliness of the text will be
- //put on index 0 in the totalUgliness array.
- for (int i = text.Length - 1; i >= 0; i--)
- {
- totalUgliness[i] = ugliness[i][text.Length - 1];
- resultIndices[i] = text.Length;
- int length = 0;
- for (int j = text.Length - 1; j >= 0 && i + j < text.Length; j--)
- {
- int jInTextArray = i + j;
- length += text[jInTextArray].Length + 1;
- //If the total ugliness from i to the end is higher than the total ugliness
- //splitted, we can better split the line at index j.
- if (length <= lineWidth && totalUgliness[i] > ugliness[i][jInTextArray - 1] + totalUgliness[jInTextArray])
- {
- totalUgliness[i] = totalUgliness[j] + ugliness[i][jInTextArray - 1];
- resultIndices[i] = jInTextArray;
- }
- }
- }
- //If the modus is 1 the string will be splitted at the indices which
- //are stored in the resultIndices array.
- if (modus == 1)
- {
- int begin = 0;
- int end = 0;
- while (end < text.Length)
- {
- end = resultIndices[begin];
- for (int k = begin; k < end; k++)
- {
- Console.Write(text[k] + " ");
- }
- Console.Write('\n');
- begin = end;
- }
- }
- //If the modus is 2 only the total ugliness of the text will be printed.
- else
- {
- Console.WriteLine(totalUgliness[0]);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement