CSP历年复赛题-P2058 [NOIP2016 普及组] 海港

原题链接:https://www.luogu.com.cn/problem/P2058

题意解读:计算24小时时间窗口内不同国家的数量,是队列的典型应用。

解题思路:

本题需要用到两个关键的数据结构:队列、数组

队列用来保存24小时内到达的船的时间,数组用来保存24小时内每个国家有多少人

每到一只船,需要把时间放入队列,如果距离队首时间超过24小时,则要出队,一直到不超过24小时

每一次入队、出队,都需要更新数组中每个国家的人数

考虑到总人数在

100分代码:

#include <bits/stdc++.h>
using namespace std;

struct node
{
    int t, x;
};

queue<node> q;
int p[100005]; //不同国家的人数
int ans;

int main()
{
    int n, t, k, x;
    cin >> n;
    while(n--)
    {
        cin >> t >> k;
        while(k--)
        {
            cin >> x;
            while(q.size() && t - q.front().t >= 86400) //如果队列不空且与队首时间超过24小时,注意>=
            {
                p[q.front().x]--; //减少队首国家的人数
                if(p[q.front().x] == 0) ans--; //更新ans
                q.pop(); //队首出队
            }

            q.push({t, x}); //当前国家的人入队
            p[x]++; //增加x国家的人数
            if(p[x] == 1) ans++; //更新答案
        }
        cout << ans << endl;;
    }   
    
    return 0;
}

 

posted @   五月江城  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示