模拟,注意Justify模式的最后一行,无论有几个单词都要用Left方式输出。
View Code
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> using namespace std; #define maxn 505 #define maxl 80 #define max_len 75 char word[maxn][maxl]; char cmd[3]; int n; int sum[maxn]; int word_len[maxn]; void input() { scanf("%s", cmd); int i = 1; while (~scanf("%s", word[i])) i++; n = i - 1; for (int i = 1; i <= n; i++) word_len[i] = strlen(word[i]); sum[0] = 0; for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + word_len[i]; } int find_end(int s) { int len = word_len[s]; int i = s + 1; while (len + word_len[i] + 1 <= max_len && i <= n) { len += word_len[i] + 1; i++; } return i; } int space_num(int s, int e) { return max_len - (sum[e - 1] - sum[s - 1]); } void left(int s, int e) { for (int i = s; i < e - 1; i++) printf("%s ", word[i]); puts(word[e - 1]); } void right(int s, int e) { int num = space_num(s, e); for (int i = 0; i < num - (e - s - 1); i++) putchar(' '); left(s, e); } void justify(int s, int e) { if (e - s == 1) { puts(word[s]); return; } if (e == n + 1) { left(s, e); return; } int num = space_num(s, e); int base = num / (e - s - 1); int extra = num % (e - s - 1); printf("%s", word[s]); for (int i = 1; i <= e - s - 1; i++) { for (int j = 0; j < base; j++) putchar(' '); if (i <= extra) putchar(' '); printf("%s", word[s + i]); } putchar('\n'); } void center(int s, int e) { int num = space_num(s, e); int temp = num - (e - s - 1); int left_space = temp / 2; for (int i = 0; i < left_space; i++) putchar(' '); left(s, e); } void work() { int s, e; e = s = 1; while (e <= n) { e = find_end(s); if (cmd[0] == 'J') justify(s, e); else if (cmd[0] == 'L') left(s, e); else if (cmd[0] == 'R') right(s, e); else center(s, e); s = e; } } int main() { //freopen("t.txt", "r", stdin); input(); work(); return 0; }