D. Connect the Dots

https://codeforces.com/problemset/problem/2020/D
题面:

思路:并查集加合并区间,然后发现一个大佬的并查集板子很好

#include <bits/stdc++.h>
using namespace std;
struct DSU {
    std::vector<int> fa, siz;
    DSU(int n) : fa(n + 1), siz(n + 1, 1) {
        std::iota(fa.begin(), fa.end(), 0);
    }
    inline int find(int x) {
        return fa[x] == x ? x : fa[x] = find(fa[x]);
    }
    inline bool same(int x, int y) {
        return find(x) == find(y);
    }
    // true if x and y were not in the same set, false otherwise.
    inline bool merge(int x, int y) {
        int fx = find(x), fy = find(y);
        if (fx == fy) return false;
        if (siz[fx] < siz[fy]) swap(fx, fy);
        fa[fy] = fx, siz[fx] += siz[fy], siz[fy] = 0;
        return true;
    }
    // x -> y, a.k.a let x be son of y (disable merge by rank).
    inline bool directed_merge(int x, int y) {
        int fx = find(x), fy = find(y);
        if (fx == fy) return false;
        fa[fx] = fy, siz[fy] += siz[fx], siz[fx] = 0;
        return true;
    }
};
int t, n, m, a, k, d;
inline void solve(void) {
    cin >> n >> m;
    vector<pair<int, int>> segs[11][11];
    for (int i = 1; i <= m; i++) {
        cin >> a >> d >> k;
        segs[d][a % d].push_back({a, a + k * d});
    }
    DSU D(n);
    int ans = n;
    for (int i = 1; i <= 10; i++) {
        for (int rem = 0; rem < i; rem++) {
            auto &seg = segs[i][rem];
            const int siz = seg.size();
            sort(seg.begin(), seg.end());
            for (int l = 0, r = 0; l < siz; l = r) {
                int L = seg[l].first, R = seg[l].second;
                while (r < siz && seg[r].first <= R) {
                    R = max(R, seg[r].second), r++;
                }
                for (int j = L; j < R; j += i) {
                    ans -= D.merge(j, j + i);
                }
            }
        }
    }
    cout << ans << '\n';
}
inline void optimizeIO(void) {
    ios::sync_with_stdio(false);
    cin.tie(NULL), cout.tie(NULL);
}
int main(int argc, char const *argv[]) {
    optimizeIO(), cin >> t;
    while (t--) solve();
    return 0;
}
posted @   WHUStar  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示