題目鏈接: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;
}