一.题目
题目描述
“饱了么”外卖系统中维护着 N 家外卖店,编号 1∼N。
每家外卖店都有一个优先级,初始时 (0时刻) 优先级都为 0。
每经过 1 个时间单位,如果外卖店没有订单,则优先级会减少 1,最低减到 0;而如果外卖店有订单,则优先级不减反加,每有一单优先级加 2。
如果某家外卖店某时刻优先级大于 5,则会被系统加入优先缓存中;如果优先级小于等于 3,则会被清除出优先缓存。
输入格式
第一行包含 3 个整数 N,M,T。
以下 M 行每行包含两个整数 ts 和 id,表示 ts 时刻编号 id 的外卖店收到一个订单。
输出格式
输出一个整数,代表答案。
数据范围
1 ≤ N,M,T ≤ 105 ,
1 ≤ ts ≤ T,
1 ≤ id ≤ N
输入样例
2 6 6
1 1
5 2
3 1
6 2
2 1
6 2
输出样例
1
样例解释
6 时刻时,1 号店优先级降到 3,被移除出优先缓存;2 号店优先级升到 6,加入优先缓存。
所以是有 1 家店 (2 号) 在优先缓存中。
二.解释
看到这种题目,我们直接模拟整个计算过程就好,但是模拟的角度有所不同:
1.从时间的角度:
我们可以模拟从 0 时刻到 T 时刻,每个时刻看看有哪些 id 在这一时刻有单在计算,但是这种算法复杂度有点超,不能全解;
2.从商家的角度:
我们遍历每个商家,取出所有这个商家的单,根据时间先后来排序,通过计算时间差来优化复杂度,可以AC。
三.代码
1.从时间的角度:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;
typedef long long int64;
typedef pair<int, int> PII;
const int MaxN = 1e5 + 10;
int InN, InM, InT, Res; //商家数量,单数量,最大时间
vector<int> Ns[MaxN]; //Ns[1]代表id为1的商家在哪些时刻有单
int Map[MaxN]; //Map[1]代表id为的优先指数
unordered_map<int, int> PList; //记录优先商家
int main()
{
cin >> InN >> InM >> InT;
int a, b;
for (int i = 1; i <= InM; i++)
{
scanf("%d%d", &a, &b);
Ns[a].push_back(b);
}
for (int i = 1; i <= InT; i++) //遍历每一时刻
{
unordered_map<int, int> M;
for (auto& Tmp : Ns[i]) //这一时刻有单
{
Map[Tmp] += 2;
M[Tmp]++;
if (Map[Tmp] > 5)
{
PList[Tmp]++;
}
}
for (int j = 1; j <= InN; j++) //这一时刻没单
{
if (!M.count(j))
{
Map[j] = max(0, Map[j] - 1);
if (Map[j] <= 3) { PList.erase(j); }
}
}
}
cout << PList.size();
return 0;
}
2.从商家的角度:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <cstring>
#include <queue>
#include <unordered_map>
#include <map>
using namespace std;
typedef long long int64;
typedef pair<int, int> PII;
const int MaxN = 2e5 + 10;
int InN, InM, InT, Res; //商家数量,单数量,最大时间
map<int, vector<int>> Ns; //Ns[1]代表id为1的商家在vector<int>时刻有单
int Map[MaxN]; //Map[1]代表id为的优先指数
unordered_map<int, int> PList; //记录优先商家
int main()
{
cin >> InN >> InM >> InT;
int a, b;
for (int i = 1; i <= InM; i++)
{
scanf("%d%d", &a, &b);
Ns[b].push_back(a);
}
for (auto& Tmp1 : Ns) //遍历每个商家
{
sort(Tmp1.second.begin(), Tmp1.second.end()); //为该商家来单时刻排序
int PerT = 0, Count = 0;
for (auto& Tmp2 : Tmp1.second) //遍历所有单
{
int TGap = Tmp2 - PerT; //计算上一单到这一单的时间差
PerT = Tmp2; //记录这一单的时间
Count = max(0, Count - (TGap == 0 ? 1 : TGap) + 1); //减去时间差,最后+1是因为Tmp2时刻有单无需减少,再特殊处理当TGap == 0的情况
if (Count <= 3 && PList.count(Tmp1.first)) { PList.erase(Tmp1.first); }
Count += 2;
if (Count > 5 && !PList.count(Tmp1.first)) { PList[Tmp1.first]++; }
}
if (PerT < InT) { Count = max(0, Count - (InT - PerT)); } //最后计算到最后时刻的有些指数
if (Count <= 3 && PList.count(Tmp1.first)) { PList.erase(Tmp1.first); }
else if (Count > 5 && !PList.count(Tmp1.first)) { PList[Tmp1.first]++; }
}
cout << PList.size();
return 0;
}