逆向思维例题——洛谷P1197 星球大战
题目:https://www.luogu.org/problemnew/show/P1197
题解:
读完题目,我们首先会想到每次删去一个点,然后重新建图,算出联通块的个数。然而,这根本不行,时间上过不去,这时就得让我们将头旋转180度,从后往前处理,也就是我们经常用的接边了。当然,再接边前需要预处理,当前这条边应当在什么时候接上,给边标上序号,然后依次处理。最后逆序输出,就可以啦。
写法一:
#include<bits/stdc++.h>
using namespace std;
const int MAXI=4e5+4;
int f[MAXI],head[MAXI],h[MAXI],ans[MAXI],En=0;
bool e[MAXI];
int find(int x){
return f[x]==x?x:f[x]=find(f[x]);
/* if(x!=f[x]) f[x]=find(f[x]);
return f[x];*/
}
struct edge{
int from,to,next;//next为前向星而设置
}a[MAXI];//a[]存边
void insert(int u,int v){//链式前向星
a[En].from=u;
a[En].to=v;
a[En].next=head[u];
head[u]=En;
En++;
}
int main(){
int n,m,k,x,y,tot,i,u;
cin>>n>>m;
for(i=0;i<n;++i){
f[i]=i;//并查集初始化
head[i]=-1;//前向星初始化
}
for(i=0;i<m;++i)
{//读入图
cin>>x>>y;
insert(x,y);insert(y,x);//无向图
}
cin>>k;
tot=n-k;//打击后剩余的点
for(i=1;i<=k;i++){
cin>>x;
e[x]=true;
h[i]=x;//存储依次被打击的点
}//读入打击点
//接下来刨除所有被打击的点建立并查集,求连通块个数
for(i=0;i<2*m;i++){//边的两点都没被打击
if(e[a[i].from]==false&&e[a[i].to]==false)
{//En是从0开始的
if(find(a[i].from)!=find(a[i].to))//不在同一并查集即不连通
{
tot--;
f[find(a[i].from)]=find(a[i].to);//开国太祖的爹是自己
}
}
}
ans[k+1]=tot;//k次打击后剩下的连通块的数目,接下来逐渐修复
for(int t=k;t>=1;t--){
u=h[t];
tot++;
e[u]=false;//恢复该点
for(i=head[u];i!=-1;i=a[i].next)//前向星遍历
{
if(e[a[i].to]==false&&find(u)!=find(a[i].to))
{//u的某条边的对点未被打击且两点不在同一并查集
tot--;
f[find(a[i].to)]=find(u);//合并
}
}
ans[t]=tot;
}
for(i=1;i<=k+1;++i) cout<<ans[i]<<endl;
return 0;
}
写法二:
#include<bits/stdc++.h>
using namespace std;
#define MAXN 200005
int n,m,fa[MAXN*2],K,D[MAXN*2],vis[2*MAXN],ans[2*MAXN],num;
//vis[]给点标号,D[]存储被攻占的点
struct xcw{
int x,y,c;//c代表这条边的序号
bool operator<(const xcw b) const{return c<b.c;}//序号从小到大排序 ,sort()中使用
}a[MAXN];
int read()
{
int ret=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();}
while(ch>='0'&&ch<='9') ret=ret*10+ch-48,ch=getchar();
return ret*f;
}
int get(int x){return fa[x]==x?x:fa[x]=get(fa[x]);}
void mer(int x,int y){//合并
int fx=get(x),fy=get(y);
if(fx!=fy) fa[fx]=fy,num--;
}
int main(){
n=read();m=read();num=n;
for(int i=0;i<n;i++) fa[i]=i;
for(int i=1;i<=m;i++) a[i]=(xcw){read(),read(),0};//结构体重载的输入赋值方法
K=read();
for(int i=1;i<=K;i++) vis[D[i]=read()]=K-i+1;//vis[]存储被摧毁的某点修复次序
for(int i=1;i<=m;i++) a[i].c=max(vis[a[i].x],vis[a[i].y]);
//当前边的序号是两个点中的较大值,序号越大越早破坏,越晚修复
sort(a+1,a+1+m);//排序过程中调用重载符 ,从小到大排序,越小越早修复
for(int i=0,j=1;i<=K;i++){//i代表修复次序 ,a[j].c=0代表未被摧毁的点,所以i=0
for(;a[j].c==i;j++) mer(a[j].x,a[j].y);
ans[i]=(num-K)+i;//K-i是被攻占星球的个数
}
for(int i=K;i>=0;i--) cout<<ans[i]<<endl;
return 0;
}