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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值