1455: 罗马游戏
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 615 Solved: 220
[Submit][Status]
Description
Input
Output
Sample Input
100 90 66 99 10
7
M 1 5
K 1
K 1
M 2 3
M 3 4
K 5
K 4
Sample Output
10
100
0
66
HINT
Source
题解:
左偏树容易看出来,但并查集的维护是不易想到的。
此题这样维护:
1.合并两个集合的时候,令fa[x]=fa[y]=merge(x,y)
2.删除最值的时候 令x=find(x),die[x]=1,fa[x]=merge(l[x],r[x]),fa[fa[x]]=fa[x]
这样做是巧妙的,值得进一步领悟。
代码:
1 #include<cstdio> 2 3 #include<cstdlib> 4 5 #include<cmath> 6 7 #include<cstring> 8 9 #include<algorithm> 10 11 #include<iostream> 12 13 #include<vector> 14 15 #include<map> 16 17 #include<set> 18 19 #include<queue> 20 21 #include<string> 22 23 #define inf 1000000000 24 25 #define maxn 2000000+1000 26 27 #define maxm 500+100 28 29 #define eps 1e-10 30 31 #define ll long long 32 33 #define pa pair<int,int> 34 35 #define for0(i,n) for(int i=0;i<=(n);i++) 36 37 #define for1(i,n) for(int i=1;i<=(n);i++) 38 39 #define for2(i,x,y) for(int i=(x);i<=(y);i++) 40 41 #define for3(i,x,y) for(int i=(x);i>=(y);i--) 42 43 #define mod 1000000007 44 45 using namespace std; 46 47 inline int read() 48 49 { 50 51 int x=0,f=1;char ch=getchar(); 52 53 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 54 55 while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();} 56 57 return x*f; 58 59 } 60 int n,m,h[maxn],l[maxn],r[maxn],fa[maxn],a[maxn]; 61 bool v[maxn]; 62 inline int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);} 63 inline int merge(int x,int y) 64 { 65 if(x*y==0)return x+y; 66 if(a[x]>a[y])swap(x,y); 67 r[x]=merge(r[x],y); 68 if(h[l[x]]<h[r[x]])swap(l[x],r[x]); 69 h[x]=h[r[x]]+1; 70 return x; 71 } 72 73 int main() 74 75 { 76 77 freopen("input.txt","r",stdin); 78 79 freopen("output.txt","w",stdout); 80 81 n=read(); 82 for1(i,n)a[i]=read(),fa[i]=i; 83 m=read(); 84 while(m--) 85 { 86 char ch[2]; 87 scanf("%s",ch); 88 if(ch[0]=='M') 89 { 90 int x=read(),y=read(); 91 if(v[x]||v[y])continue; 92 x=find(x);y=find(y); 93 if(x==y)continue; 94 int t=merge(x,y); 95 fa[x]=fa[y]=t; 96 } 97 else 98 { 99 int x=read(); 100 if(v[x]){printf("0\n");continue;} 101 x=find(x);v[x]=1;printf("%d\n",a[x]); 102 fa[x]=merge(l[x],r[x]); 103 fa[fa[x]]=fa[x]; 104 } 105 } 106 107 return 0; 108 109 }