Multithread 优先队列 + 模拟

链接:https://ac.nowcoder.com/acm/contest/560/G
来源:牛客网
 

题目描述

Sleep Sort is a sorting method described below:
 

 let A = array to be sorted
 let q = thread-safe queue
 for each v in A :
     create a new thread executing :
         sleep(v seconds)
         q.push(v)


DK's computer is extremely high-tech so that
1. the time of sleeping is absolutely accurate.
2. only the push operation (q.push(v)) and sleep operation executed non-instantly.
3. threads scheduling does not affect this sorting.

DK's magic thread-safe queue has to work on the q.push(v) operation for exact ceil(sqrt(v)) seconds.
During this time other thread which intends to use the queue has to wait for it until it finishes, and then take control of the queue.
When a thread finishes pushing and there are multiple threads waiting, the next one is chosen randomly, which may bring a wrong result.

Given an array A, check whether DK's Sleep Sort may cause a wrong result.

输入描述:

The first line contains an integer n, the length of array A.

The next line contains n integers, representing elements of A.

(1≤n≤1000000,0≤Ai≤109)

题解:把到达某一时刻符合的数放到优先队列中,每次pop出最大的那个,若出队列的数小于之前pop出的数,则不符合

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int n,a[N];
struct node{
	int t;
	node(){
	}
	node(int t_)
	{
		t=t_;
	}
	bool operator <(const node &xx)const
	{
		return t<xx.t;
	}
};
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1,a+1+n);
	int t=a[1];
	int pre=0;
	priority_queue<node> q;
	node now;
	int flag=1;
	for(int i=1;i<=n;)
	{
		while(i<=n&&a[i]<=t)
		{
			q.push(node(a[i]));
			i++;
		}
		if(q.empty())
		{
			if(i<=n) t=a[i];
		}
		else
		{
			now=q.top();q.pop();
		//	cout<<now.t<<" "<<pre<<endl;
			if(now.t<pre)
			{
				flag=0;
				break;
			}
			else
			{
				pre=now.t;
				t+=ceil(sqrt(now.t*1.0));
			}
		}
	}
	while(!q.empty())
	{
		now=q.top();
		q.pop();
		if(now.t<pre)
		{
			flag=0;
			break;
		}
		else
		{
			pre=now.t;
		}	
			
	} 
	printf(flag?"1\n":"0\n");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/89284113