类似冒泡排序法(ZOJ 1730)
http://blog.csdn.net/yzl_rex/article/details/7391777
- 如果所有人是线性排列,那我们的工作就是类似冒泡程序做的工作:1,2,3,4,5变为5,4,3,2,1 ,耗时n(n-1)/2
- 但是出现了环,也就是说1,2,3,4,5变为3,2,1,5,4也可满足条件
- 我们可以把这个环等分成两个部分(四部分不行了,圆的头与尾接不上了) ,每个部分看成是线性的,再把它们花的时间加起来.
- 当n是偶数时, 每份人数n/2 ,即 2*(n/2 )*(n/2 -1)/2;
- 当n是奇数时,两份的人数分别是n/2和n/2+1,即(n/2)*(n/2 -1)/2 + (n/2 +1)*(n/2)/2
import java.io.*; import java.util.*; import java.math.*; public classMain { int t, n; void run() { t = cin.nextInt(); while (t-- > 0) { n = cin.nextInt(); if ((n & 1) > 0) System.out.println(n / 2 * (n / 2 - 1) / 2 + n / 2 * (n / 2 + 1) / 2); else System.out.println(2 * n / 2 * (n / 2 - 1) / 2); } } public static void main(String[] args) { Mainsolved = new Main(); solved.run(); } static InputStreaminputStream = System.in; static InputReadercin = new InputReader(inputStream); // Scanner cin = new Scanner(new BufferedInputStream(System.in)); } classInputReader { private InputStreamstream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStreamstream) { this.stream = stream; } public int read() { if (numChars == -1) return -1; //throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOExceptione) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); if (c == -1) return -1; while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public Stringnext() { StringBuilderstr = new StringBuilder(); int ch; while (isSpaceChar(ch = read())); if (ch == -1) return null; do { str.appendCodePoint(ch); } while (!isSpaceChar(ch = read())); return str.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } }