跳到正文

题解

题解 AT1998 【[AGC002D] Stamp Rally】

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

文章信息

收录
2026年6月14日
更新
2026年7月10日
篇幅
约 4 分钟
获赞
4

版本

  1. v1当前

其实这道题有一个很暴力的方法。

很容易想到离线加边,判断每一个询问是否满足条件,但必须每次检查每一个询问,时间复杂度 O(mqlog⁡n)O(mq\log n)。

上述过程每一次检验非常浪费时间,考虑分块,每插入 O(m)O(\sqrt m) 次检验一次,对于每一个询问倒着扫一遍用带撤销并查集断一下就行了。

时间复杂度 O(qmlog⁡n)O(q\sqrt m\log n) 常数较小。

C++
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define re register
using namespace std;
const int Mxdt=100000;	//单次大小 
inline char gc(){
	static char buf[Mxdt],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,Mxdt,stdin),p1==p2)?EOF:*p1++;
}
inline char pc(char ch,bool bj){
	static char buf[Mxdt],*p1=buf,*p2=buf+Mxdt;
	return (bj||(*p1++=ch)&&p1==p2)&&fwrite(p1=buf,1,p1-buf,stdout),0;
}
void print(int x)
{
	if(x>9)print(x/10);
	pc(x%10^48,false);
}
inline void printnum(int x,char ch)
{
	print(x),pc(ch,false);
}
inline int read(){
	re int t=0;re char v=gc();
	while(v<'0')v=gc();
	while(v>='0')t=(t<<3)+(t<<1)+v-48,v=gc();
	return t;
}
int fa[100002],n,m,q,a[100002],b[100002],A[100002],B[100002],C[100002],ans[100002],siz[100002],tp,stkx[100002],stky[100002],t[100002],aa[100002],bb[100002],sss,cc[100002];
inline int root(re int x){return x==fa[x]?x:root(fa[x]);}
inline void merge(re int x,re int y,re int z){
	if((x=root(x))==(y=root(y)))return;
	if(siz[x]>siz[y])swap(x,y);
	fa[x]=y,stkx[++tp]=x,stky[tp]=y,siz[y]+=siz[x],t[tp]=z;
}
inline void undo(){
	siz[stky[tp]]-=siz[stkx[tp]];
	fa[stkx[tp]]=stkx[tp];
	--tp;
}
inline bool check(re int x){
	re int xx=root(A[x]),yy=root(B[x]);
	if(xx==yy)return siz[xx]>=C[x];
	return (siz[xx]+siz[yy])>=C[x];
}
int main(){
	n=read(),m=read();
	for(re int i=1;i<=n;++i)siz[fa[i]=i]=1;
	for(re int i=1;i<=m;++i)a[i]=read(),b[i]=read();
	q=read();
	for(re int i=1;i<=q;++i)A[i]=read(),B[i]=read(),C[i]=read();
	re int ss=sqrt(m),lst=0;
	for(re int i=1;i<=m;++i){
		merge(a[i],b[i],i);
		if(i%ss==0||(i==m)){
			for(re int j=1;j<=q;++j)
				if(!ans[j]){
					re int pos=i;sss=0;
					while(check(j)){
						if(pos==t[tp])undo();
						ans[j]=pos;--pos;
					}
					for(re int k=pos;k<=i;++k)merge(a[k],b[k],k);
				}
			lst=i;
		}
	}
	for(re int i=1;i<=q;++i)printnum(ans[i],'\n');
	return pc('o',1);
}
原文
存档评论1 条抓取于