(上p30の計算量重視版)

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=10031