题解:T633237 『欢乐暑假』防洪水

· · 题解

说在前面

冷知识:防洪水谐音放洪水。

赛时没过的敲个 6 我看看。

前置芝士:双指针。

题目分析

大水题,首先对 a 和 b 分别排个序,然后双指针。若当前的 b _ j < a _ i,那么就一直移动 j 直到 j > m 或 b _ j \ge a _ i,随后计数器 cnt 加一,直到 i > n。最后如果 cnt = n,输出 YES,否则输出 NO,然后在下一行输出 cnt。

时间复杂度 O(n + m)。

完整代码

#include <bits/stdc++.h>

#define int long long

using namespace std;

const int N = 1000000 + 5;

int a[N], b[N];

int n, m;

signed main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i <= m; i++) {
        cin >> b[i];
    }
    sort(a + 1, a + n + 1);
    sort(b + 1, b + m + 1);
    int pos1 = 1, pos2 = 1;
    int cnt = 0;
    while (pos1 <= n) {
        while (pos2 <= m && b[pos2] < a[pos1]) {
            pos2++;
        }
        if (pos2 > m) break;
        cnt++;
        pos1++;
        pos2++;
    }
    if (cnt == n) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
        cout << cnt << endl;
    }
    return 0;
} 

说在后面

若代码,思路讲解有误,欢迎提出!