juggler
time limit (normal/java): 1000ms/3000ms Run memory limit: 65536KByte
Description
As part of the My Magical juggling act, I am currently juggling a number of objects in a circular path with one hand. However, as my rather elaborate act ends, I wish to drop all of the objects in a specific order, in a minimal amount of TI Me. On each move, I can either rotate all of the objects counterclockwise by one, clockwise by one, or drop the object current Ly in my hand. If I Drop the object currently in my hand, the next object (clockwise) would fall into my hand. What's the minimum number of moves it takes to drop all of the balls I ' m juggling?
input
There'll is several test cases in the input. Each test case is begins with a integern, (1≤n≤100,000) on its own line, and indicating the total number of BA LLS begin juggled. Each of the next n lines consists of a single integer,kI (1≤ki≤n), which describes a single bal L:i is the position of the ball starting clockwise from the Juggler ' s hand, andKI are the order in which the ball should be dropped. The set of numbers {K1,K 2, ...,kn} is guaranteed to be a permutation of the numbers 1. n. The input would terminate with a line containing a single 0.
Output
For each test case, output a single integer in its own line, indicating the minimum number of moves I need to drop all of The balls in the desired order. Output no extra spaces, and do not separate answers with blank lines. All possible inputs yield answers which would fit in a signed 64-bit integer.
Sample Input
3
3
2)
1
0
Sample Output
5
Tips
Explanation of the input:the first ball was in the juggler ' s hand and should being dropped third; the second ball I s immediately clockwise from the first ball and
should being dropped second; the third ball was immediately clockwise from The second ball and should is dropped last.
A few
are removed from the tree-like array record interval.
#include <stdio.h> #include <string.h> const int MAX = 100010;
int n;
int A[max];
int Map[max];
int min (int x,int y) {return x < y x:y;} int lowbit (int t) {return T & (t ^ (t-1));
} int sum (int end) {int sum = 0;
while (end > 0) {sum + = A[end];
End-= lowbit (end);
} return sum;
} void Plus (int pos, int num) {while (pos <= n) {A[pos] + = num;
pos + = Lowbit (POS);
}} int main () {int i,x,s;
while (scanf ("%d", &n), N) {memset (a,0,sizeof (a));
for (i = 1; I <= n; i++) {scanf ("%d", &x);
MAP[X] = i;
} int k = 1;
__int64 cnt = n;
for (i = 1;i < n; i++) {if (i = = 1) s = map[i]-1;
else if (K < map[i]) s = map[i]-K-(SUM (map[i))-sum (k))-1;
else S = k-map[i]-(SUM (k-1)-sum (Map[i]-1));
Plus (map[i],1);
CNT + = min (S,n-i-S + 1);
k = Map[i];
} printf ("%i64d\n", CNT);
} return 0; }