C++ takeaway priority (simulation)

There are N take-out shops maintained in the "Is it full" take-out system, numbered 1∼N.
Each takeaway store has a priority, and the priority is 0 at the beginning (at time 0). After
each time unit, if the takeaway shop has no order, the priority will be reduced by 1, and the lowest will be reduced to 0; if the takeaway shop has an order, the priority will not decrease but increase, and the priority will increase by 2 for each order.
If the priority of a takeaway restaurant is greater than 5 at a certain time, it will be added to the priority cache by the system; if the priority is less than or equal to 3, it will be cleared from the priority cache.
Given the M pieces of order information within time T, please calculate how many takeaway shops are in the priority cache at time T.
Input format The
first line contains 3
integers N, M, T.
Each line of the following M lines contains two integers ts and id, indicating that the takeaway store with the number id at time ts received an order.
Output format
Output an integer to represent the answer.
Data range
1≤N,M,T≤105,1≤ts≤T,1≤id≤N
Input example:
2 6 6
1 1
5 2
3 1
6 2
2 1
6 2
Output example:
1
example explanation
At 6
o'clock, the priority of No. 1 shop drops to 3 and is removed from the priority cache; the priority of No. 2 shop rises to 6, and the priority cache is added. So there is 1 store (No. 2) in the priority cache.

This question can use sorting to process orders from the same store at the same time to improve efficiency.

AC code:

#include<stdio.h>
#include<algorithm>

using namespace std;

const int N=100010;

int last[N];//上次接到订单的时候
pair<int,int> order[N];//订单
int score[N];//优先级
bool exist[N];//是否在缓存中

int main()
{
    
    
    int n,m,T;
    scanf("%d%d%d",&n,&m,&T);
    for(int i=0;i<m;++i)
        scanf("%d%d",&order[i].first,&order[i].second);
    //STL默认用升序排列,时刻早、店序号的排前面
    sort(order,order+m);
    
    for(int i=0;i<m;)
    {
    
    
        //寻找同时刻同家店的订单
        int j=i;
        while(j<m&&order[j]==order[i]) ++j;
        //获得该时刻和该店序号,计算订单数
        int t=order[i].first,id=order[i].second,cnt=j-i;
        //j刚好指向第一个不是同时刻同家店的订单
        i=j;
		
		//处理t时刻前的消息
        score[id]-=t-last[id]-1;//计算没接到订单的时间,修改优先级
        if(score[id]<0) score[id]=0;
        if(score[id]<=3) exist[id]=false;
		
		//处理t时刻消息
        score[id]+=2*cnt;//接到订单,优先级增加
        if(score[id]>5) exist[id]=true;
        last[id]=t;//修改最后一次接到订单的时刻
    }

    for(int i=1;i<=n;++i)//处理T时刻的信息
    {
    
    
        if(last[i]<T){
    
    
            score[i]-=T-last[i];
            if(score[i]<=3) exist[i]=false;
        }
    }

    int ans=0;//统计答案
    for(int i=1;i<=n;++i)
        if(exist[i]) ++ans;
    printf("%d",ans);

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108891327