B. Multithreading

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.

Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.

Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.

Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:

  1. thread x is not updated (it has no new messages);
  2. the list order 1, 2, ..., n changes to a1a2, ..., an.

Input

The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 105). The next line contains a list of n space-separated integers a1a2, ..., an where ai (1 ≤ ai ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.

Output

Output a single integer — the number of threads that surely contain a new message.

Sample test(s)
input
5
5 2 1 3 4
output
2
input
3
1 2 3
output
0
input
4
4 3 2 1
output
3
Note

In the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.

In the second test case, there may be no new messages at all, since the thread order hasn't changed.

In the third test case, only thread 1 can contain no new messages.


解题说明:这道题描述的是一个消息推送队列,没有阅读的消息会提示在上面,而阅读过后的消息会按照序号从小到大排列,题目要求我们找出最可能没有阅读的消息。思想是找出从1到n这个数字队列中找出不符合排列的数字个数,比如针对 1 2 5 3 4这个消息队列,阅读完后应该是1 2 3 4 5,现在5在3,4的前面,表明5未阅读,进而推出前面的1 2 也未阅读,即使1和2顺序是对的。为此我们需要从后向前遍历,找到第一个不符合a[i]<a[i+1]的数字,然后就可以确定前面的消息都未被阅读了。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
	int n,i;
	int count;
	int flag;
	int a[100001];
	scanf("%d",&n);
	count=0;
	flag=0;
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	for(i=n-1;i>0;i--)
	{
		if(a[i-1]>a[i])
		{
			count=i;
			break;
		}
	}
	printf("%d\n",count);
    return 0;
}


你可能感兴趣的:(B. Multithreading)