题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3563
题意:银河系中,星球受到怪兽的侵略,一个星球需要向防御能力比他强且与他相连的星球求救,问是那个星球?但是,其中的某些边可能会受到破坏。
思路:这个算是一个反向思维吧,只要知道反向操作后,仔细一想,就会发现,顺序操作是删边,反向操作的就是加边,而逐一加边这一操作就是并查集的典型特征。最后只要处理合并时的顺序就行了。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
struct edge{
int a,b;
bool operator <(const edge &t)const{
if(a!=t.a) return a<t.a;
return b<t.b;
}
}E[20010];
map<edge,int> mp;
vector<int> ans;
int N,M,Q,P[10010];
int D[50010],vis[50010];
int pre[10010];
char s[10],op[50010];
int find(int x){
int t=x;
while(t!=pre[t]) t=pre[t];
while(x!=t) pre[x]=t,x=pre[x];
return t;
}
void join(int k){
int x=E[k].a,y=E[k].b;
int fx=find(x),fy=find(y);
if((P[fx]<P[fy] || (P[fx]==P[fy])&&fx>fy)) swap(fx,fy);//按要求合并
pre[fy]=fx;
}
int query(int x){
int fx=find(x);
if(P[fx]<=P[x]) return -1;
return fx;
}
int main(){
//freopen("D:\\in.txt","r",stdin);
int kase=0;
while(cin>>N){
if(kase++) cout<<endl;
memset(vis,0,sizeof(vis));
for(int i=0;i<=N;i++) pre[i]=i;
mp.clear();
for(int i=0;i<N;i++) scanf("%d",&P[i]);
cin>>M;
int a,b;
for(int i=0;i<M;i++){
scanf("%d %d",&a,&b);if(a>b) swap(a,b);//注意排序
E[i]=(edge){a,b};
mp[E[i]]=i;
}
cin>>Q;
for(int i=0;i<Q;i++){//记录Q的相关询问操作
scanf("%s",s);op[i]=s[0];
if(s[0]=='d'){
scanf("%d %d",&a,&b);
if(a>b) swap(a,b);//与前面的排序相对应
D[i]=mp[(edge){a,b}];
vis[D[i]]=1;//记录其边序号
}else{
scanf("%d",&a);
D[i]=a;//记录询问的对象
}
}
for(int i=0;i<M;i++) if(!vis[i]) join(i);//把没有删除的边先建并查集
ans.clear();
for(int i=Q-1;i>=0;i--){//反方向执行询问操作
if(op[i]=='d') join(D[i]);
else ans.push_back(query(D[i]));
}
for(int i=ans.size()-1;i>=0;i--)
printf("%d\n",ans[i]);
}
return 0;
}