跳到正文

题解

题解:P17137 [KOI 2026 #1] 朋友

#SUSPENDED#约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年8月2日
收录
2026年8月5日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
1
题目
P17137

版本

  1. v1当前

本蒟蒻第一次写题解,码丑勿喷。

题目大意:

有 NN 个学生,每人住在唯一坐标 XiX_i,读学校 SiS_i。
两人 i≠ji≠j 是朋友满足下面任意一条:

  1. 同一所学校,坐标距离 ∣Xi−Xj∣≤K1|X_i-X_j| \le K_1;
  2. 不同学校,坐标距离 ∣Xi−Xj∣≤K2|X_i-X_j| \le K_2。
    对每个学生,输出他一共有多少个朋友(不算自己)。

思路(对应代码):

假设当前学生坐标 xx,学校 ss:
all:所有在 [x−K2,x+K2][x-K_2, x+K_2] 的总人数(距离≤K2≤K_2的所有人)
cross:学校在 [x−K2,x+K2][x-K_2, x+K_2] 的人数(区间内同校人)
same:学校在 [x−K1,x+K1][x-K_1, x+K_1] 的人数(同校且距离 ≤K1≤K_1)。
条件:
异校朋友:区间 K2K_2 里不是本校的人→→all−-cross。
同校朋友:区间 K1K_1 内本校所有人 →→same。
总朋友 ==(all−-cross)++same−1-1,−1-1 是减去自己本身。

复杂度:

排序:O(Nlog⁡N)O(N\log N)。
每个点三次二分:O(Nlog⁡N)O(N\log N)。
总复杂度 O(Nlog⁡N)O(N\log N),通过 5×1055\times 10^5 的数据轻轻松松。

代码

代码加注释。

AC Code
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
//快读模板
inline int read() {
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }return x * f;
}struct Student {
    ll x;
    int s, id;
} st[500005];
vector<ll> allX;
vector<ll> sch[500005];
int ans[500005];
int N;
ll K1, K2;
// 在有序数组a中,[L,R]数字个数
int count(vector<ll>& a, ll L, ll R) {
    auto l = lower_bound(a.begin(), a.end(), L);
    auto r = upper_bound(a.begin(), a.end(), R);
    return r - l;
}int main() {
    N = read();
    K1 = read(); K2 = read();
    for (int i = 0; i < N; i++) {
        st[i].x = read();
        st[i].s = read();
        st[i].id = i;
        allX.push_back(st[i].x);
        sch[st[i].s].push_back(st[i].x);
    }sort(allX.begin(), allX.end());
    // 每个学校坐标排序
    for (int i = 1; i <= N; i++)sort(sch[i].begin(), sch[i].end());
    for (int i = 0; i < N; i++) {
        ll X = st[i].x;
        int S = st[i].s;
        // all:[X-K2,X+K2] 全局总人数
        int all = count(allX, X - K2, X + K2);
        // same:同校 [X-K1,X+K1]
        int same = count(sch[S], X - K1, X + K1);
        // cross:同校 [X-K2,X+K2]
        int cross = count(sch[S], X - K2, X + K2);
        int res = (all - cross) + same - 1; // -1 去掉自己
        ans[st[i].id] = res;
    }for (int i = 0; i < N; i++)cout << ans[i] << " ";
    return 0;
}

大佬点个赞在走吧。

原文