跳到正文

题解

P2058 [NOIP 2016 普及组] 海港题解

paoxingseal约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年2月5日
更新
2026年2月5日
篇幅
约 5 分钟
题目
P2058

版本

  1. v2当前
  2. v1

内容大意

对于每一条船,上面有ti时间和ki乘客数两个参数,后面有n名乘客相对应的国籍。

你要对此前86400秒的乘客国籍数做一个统计

C++
struct shipp {//每一艘船的信息
	int time;//到来的时间
	vector < int > country;//用vector动态数组来存储每一名乘客的国籍
};

分析

1、预处理(main函数外)

C++
#include <bits/stdc++.h>
#define int long long//数据范围需要long long
using namespace std;
const int N = 5e5 + 15;//长度(船只数量)
const int S = 86400;//24小时=86400秒
int n;//船只数量
struct shipp {//每一艘船的信息
    int time;
    vector < int > country;
};
int vis[N];//标记数组
int total;//范围内的乘客国籍数
signed main() //不能用int main ()

2、读入

C++
    cin >> n;//n
    deque < shipp > d;//每一艘船的信息
    for (int i = 1;i <= n;i++) {//循环
	int timee;//时间
	int peoplenumberr;//人数
	int countryy;//每人的国籍
	cin >> timee >> peoplenumberr;//ti和ki
	vector < int > cs;//动态数组乘客数
	while (peoplenumberr --) {//循环
		cin >> countryy;//读入国籍
		cs.push_back (countryy);//插入国籍
	}

3、入队

C++
        d.push_back ({timee,cs});//导入信息
	for (auto & k:cs) {//遍历
	    if  (vis[k] == 0) {//如果此前并没有这种国籍的人
		total ++;//人种数加1
	    }
	    vis[k] ++;//这种国籍的人数加1
	}

4、出队

C++
        while (!d.empty ()) {//直到d不为空
            shipp topp = d.front ();//topp来存队头那艘船的信息
            if (timee - topp.time >= S) {//如果超出了86400秒
                for (auto & k:topp.country) {//循环遍历
                    vis[k] --;//人数减一
                    if (vis[k] == 0) {//如果这个国家的人都不存在了
                        total --;//总人种数减一
                    }
                }
                d.pop_front ();//头部pop ()
            } else {
                break;//为什么要break?因为如果队头都能满足(双端队列是递增的),那么后面队尾(这个时间点后面的船只)也一定能够在范围内
            }
        }

5、输出

C++
cout << total << "\n" ;

完整代码如下:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 5e5 + 15;
const int S = 86400;
int n;
struct shipp {
	int time;
	vector < int > country;
};
int vis[N];
int total;
signed main() {
	cin >> n;
	deque < shipp > d;
	for (int i = 1;i <= n;i++) {
		int timee;
		int peoplenumberr;
		int countryy;
		cin >> timee >> peoplenumberr;
		vector < int > cs;
		while (peoplenumberr --) {
			cin >> countryy;
			cs.push_back (countryy);
		}
		d.push_back ({timee,cs});
		for (auto & k:cs) {
			if  (vis[k] == 0) {
				total ++;
			}
			vis[k] ++;
		}
		while (!d.empty ()) {
			shipp topp = d.front ();
			if  (timee - topp.time >= S) {
				for (auto & k:topp.country) {
					vis[k] --;
					if  (vis[k] == 0) {
						total --;
					}
				}
				d.pop_front ();
			} else {
				break;
			}
		}
		cout << total << "\n" ;
	}
    return 0;
}


原文