AOJ1115 Multi-column List

問題リンク Multi-column List

  • 概要

文章がいくつか与えられるので、それをmulti-column listとして出力せよ。
このリストは1ページにつき、高さplen、横幅widthのカラムがcnum個続いている。カラムの間にはcspace個の空白が入る。文章が1行に入り切らない場合次の行に続きを書く。1つのカラムが埋まったら次のカラムに移る。cnum個のカラムを埋めきったら次のページに移るものとする。
1 <= plen <= 100
1 <= (cnum * width + cspace * (cnum - 1)) <= 50

  • 解法

plenとか正直ややっこしいので図にしてみました。

どんなテキスト帳か想像できましたか?
実装の方針としては、String[cnum][plen]で1つのページを表すことです。文字を読み込むたび、plen側のインデックスを増やします。widthをはみ出した分については、はみ出た分を「次の入力で受け取った文章だよ!」と見なすことで例外的な処理を避けています。plenを使い切ったらcnumを増やして次のカラムへ移ります。cnumまでも埋まりきったら、その場で1ページ分の出力処理をします。そしてString[cnum][plen]を初期化して次のページの処理に入ります。これを繰り返します。

  • ソース
import java.util.Scanner;

//Multi-column List
public class AOJ1115 {

	void run(){
		Scanner sc = new Scanner(System.in);
		for(;;){
			int line = sc.nextInt();
			if(line==0)break;
			int col = sc.nextInt();
			int w = sc.nextInt();
			int space = sc.nextInt();
			String sp = "";
			while(sp.length()<space)sp+=".";
			sc.nextLine();
			boolean con = true;
			String s = "";
			while(con){
				if("".equals(s)){
					s = sc.nextLine();
					if("?".equals(s))break;
				}
				String[][] res = new String[col][line];
				for(int c=0;c<col;c++){
					for(int l=0;l<line;l++){
						res[c][l] = "";
						if(!con){
							while(res[c][l].length()<w)res[c][l]=res[c][l]+".";
							continue;
						}
						if("".equals(s)){
							s = sc.nextLine();
							if("?".equals(s)){
								con = false;
								s = "";
							}
						}
						int t = Math.min(s.length(), w);
						res[c][l] = s.substring(0, t);
						while(res[c][l].length()<w)res[c][l]=res[c][l]+".";
						s = s.substring(t, s.length());
					}
				}
				for(int l=0;l<line;l++){
					for(int c=0;c<col;c++){
						System.out.print(res[c][l]+(c==col-1?"\n":sp));
					}
				}
				System.out.println("#");
			}			
			System.out.println("?");
		}
	}
	
	public static void main(String[] args) {
		new AOJ1115().run();
	}
}