跳到正文

题解

ABC409F 题解

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

文章信息

发布
2025年6月8日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
4

版本

  1. v1当前

思路

看到合并肯定有个并查集。难点在于如何高效进行操作二。

由于每次要取出当前距离最小的一批点对,所以考虑维护点对的小根堆,排序关键字是点对距离。进行操作一时把新点和所有旧点构成的对推入堆中,进行操作二时持续取出堆顶的点对合并直至出现不同的距离即可。时间复杂度 O((N+Q)2log⁡(N+Q))O((N+Q)^2\log(N+Q))。

控诉卡常题,用 set、multiset、map 的做法基本都会超时,只能使用 priority_queue。

代码

C++
#include<bits/stdc++.h>
#define gc getchar
#define eb emplace_back
#define ef emplace_front
#define ep emplace
#ifndef DEBUG
#define debug
#endif
using namespace std;
template<typename T>void read(T &x){x = 0;int f = 1;char c = gc();while(!isdigit(c)){if(c == '-') f = -1;c = gc();}while(isdigit(c)) x = x * 10 + c - '0',c = gc();x *= f;}
const int N = 4000;
int n,m,op,u,v,f[N],cnt,x[N],y[N],ans;
priority_queue<tuple<int,int,int>,vector<tuple<int,int,int>>,greater<tuple<int,int,int>>>q;
int find(int x){return x == f[x] ? x : f[x] = find(f[x]);}
int main(){
  read(n),read(m);
  for(int i = 1;i < N;i ++) f[i] = i;
  for(int i = 1;i <= n;i ++) read(x[i]),read(y[i]);
  for(int i = 1;i < n;i ++) for(int j = i + 1;j <= n;j ++) 
    q.ep(abs(x[i] - x[j]) + abs(y[i] - y[j]),i,j);//每个点对都推入优先队列
  for(int i = 1;i <= m;i ++){
    read(op);
    if(op == 1){
      read(u),read(v),x[++ n] = u,y[n] = v;//记录新点
      for(int i = 1;i < n;i ++) q.ep(abs(x[i] - u) + abs(y[i] - v),i,n);//所有新点对推入优先队列
    }
    else if(op == 2){
      ans = -1;//记录要输出的 k 值
      while(q.size()){
        auto [a,b,c] = q.top();
        if(~ans && (ans ^ a)) break;//出现了距离 >k 的点对,不再合并
        q.pop();
        if(find(b) ^ find(c)) f[find(b)] = find(c),ans = a;//如果是未合并的点对,合并并记录 k=a
      }
      printf("%d\n",ans);
    }
    else{
      read(u),read(v);
      if(find(u) == find(v)) printf("Yes\n");
      else printf("No\n");
    }
  }
  return 0;
}

submission
map 离散死亡回放

原文
存档评论1 条抓取于