题目链接:
思路:把数字全部列出来模拟一下如下,+ 表示这个数这次放到下面,o 表示这个数这次拿走,x表示这个数已经被拿走
3 7 6 2 3 1 2 6
+ + + + + o o +
+ + + o o x x +
o + o x x x x o
x o
发现只需要记录一下数字出现的位置然后根据这个数位置与上一个数位置判断这次是拿走还是放到下面,而对于多个相同元素则将所有位置记录下来,按序比较即可。
需要注意的是如上面那个例子中的两个 2 ,需要记录的是第一个2的位置,即对于上个1的位置laindex, 如果2在laindex之前出现,则记录laindex之前最大的,否则记录的是之后最大的(相当于一个一个数过去的)。
另外:100 001 * 50 000 爆 。。。。
代码:
1 #define maxn 100010 2 int n; 3 int a[maxn]; 4 priority_queue ind[maxn]; 5 6 int main(){ 7 memset(a, 0, sizeof(a)); 8 int maxa = 0; 9 scanf("%d", &n);10 for(int i = 0; i < n; i++){11 scanf("%d", &a[i]);12 maxa = max(a[i], maxa);13 ind[a[i]].push(i + 1);14 }15 int laind = 0, lak = 1;16 long long ans = 0;17 for(int i = 1; i <= maxa; i++){18 int lm = 0, bm = 0;19 if(ind[i].size() == 0)20 continue;21 while(!ind[i].empty()){22 int tmind = ind[i].top();23 if(tmind > laind){24 if(bm == 0) 25 bm = tmind;26 ans += lak;27 }28 else{29 if(lm == 0) 30 lm = tmind;31 ans += lak + 1;32 }33 ind[i].pop();34 }35 if(lm != 0){36 laind = lm;37 lak += 1;38 }39 else{40 laind = bm;41 }42 }43 printf("%lld\n", ans);44 }
题目:
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.
You are to determine the total number of times Vasily takes the top card from the deck.
The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck.
The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), where ai is the number written on the i-th from top card in the deck.
Print the total number of times Vasily takes the top card from the deck.
4 6 3 1 2
7
1 1000
1
7 3 3 3 3 3 3 3
7
In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.