Question Link
N people sit in a ring, and the adjacent two can exchange positions. The minimum number of exchanges leads to the opposite of the sequence.
Idea: similar to Bubble sorting, the circular sequence can be split into two sequences for bubble respectively. When N is an odd number, it is divided into n/2 and N/2 + 1, so ans = (n/2) * (N/2-1) /2 + (n/2) * (N/2 + 1)/2. When n is an even number, it is divided into two n/2, so ans = (n/2) * (N/2-1 ).
Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int n;int main() { int cas; scanf("%d", &cas); while (cas--) { scanf("%d", &n); if (n == 1 || n == 2) printf("0\n"); else { int ans; if (n % 2 == 0) { ans = (n / 2) * (n / 2 - 1); printf("%d\n", ans); } else { ans = (n / 2) * (n / 2 - 1) / 2 + (n / 2) * (n / 2 + 1) / 2; printf("%d\n", ans); } } } return 0;}
Uva1315-crazy Tea Party (derivation)