baru003のブログ

baruの雑記兼備忘録

AOJ 0102

・問題リンク Matrix-like Computation

・コメント
素直に解いて見ました(笑)
工夫した点・・・あまり処理時間のことが分からなくて、2重のループ使って解くのはTLEが怖かったので2次元配列を回避するようにしたことですかね。
そのぶん仕事が増えましたがなんとか上手くいったのでよしとしましょうw
少しずつjavaにも慣れ始めたような気がしてきましたが、まだまだコレクションなどのクラスライブラリを扱えていないので少しずつ出来るようにしていきたいです。

・ソース

import java.util.*;

public class P0102 {

	static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		int n;
		while (sc.hasNext()) {
			n = sc.nextInt();
			if (n == 0)
				break;
			int[] v = new int[n * n];// 入力用の箱
			int[] h = new int[n];// 横合計値用の箱
			int[] f = new int[n];// 縦合計値用の箱
			// 値入力
			int temph = 0;// 横保持値
			int j = 0;
			int cnt = 0;
			int ans = 0;
			// 入力
			for (int i = 0; i < n * n; i++) {
				v[i] = sc.nextInt();
				// 横関連
				temph += v[i];
				if ((i + 1) % n == 0) {
					h[j] = temph;
					ans += h[j];
					temph = 0;
					j++;
				}
				// 縦関連
				f[cnt] += v[i];
				cnt++;
				if ((cnt + 1) > n)
					cnt = 0;
			}
			// 出力
			int c = 0;
			int z = 0;
			for (int i = 0; i < n * n; i++) {
				System.out.printf("%5d", v[i]);
				c++;
				if (c == n) {
					System.out.printf("%5d\n", h[z]);
					z++;
					c = 0;
				}
			}
			for (int i = 0; i < n; i++) {
				System.out.printf("%5d", f[i]);
			}
			System.out.printf("%5d\n", ans);
		}
	}
}