2843: 極地旅行社
Time Limit: 10 Sec Memory Limit: 256 MB
Submit: 282 Solved: 193
Description
不久之前,Mirko建立了一個旅行社,名叫“極地之夢”。這家旅行社在北極附近購買了N座冰島,並且提供觀光服務。當地最受歡迎的當然是帝企鵝了,這些小傢伙經常成羣結隊的遊走在各個冰島之間。
Mirko的旅行社遭受一次重大打擊,以至於觀光遊輪已經不划算了。旅行社將在冰島之間建造大橋,並用觀光巴士來運載遊客。Mirko希望開發一個電腦程序來管理這些大橋的建造過程,以免有不可預料的錯誤發生。
這些冰島從1到N標號。一開始時這些島嶼沒有大橋連接,並且所有島上的帝企鵝數量都是知道的。每座島上的企鵝數量雖然會有所改變,但是始終在[0, 1000]之間。
你的程序需要處理以下三種命令:
1.”bridge A B”——在A與B之間建立一座大橋(A與B是不同的島嶼)。由於經費限制,這項命令被接受,當且僅當A與B不聯通。若這項命令被接受,你的程序需要輸出”yes”,之後會建造這座大橋。否則,你的程序需要輸出”no”。
2.”penguins A X”——根據可靠消息,島嶼A此時的帝企鵝數量變爲X。這項命令只是用來提供信息的,你的程序不需要回應。
3.”excursion A B”——一個旅行團希望從A出發到B。若A與B連通,你的程序需要輸出這個旅行團一路上所能看到的帝企鵝數量(包括起點A與終點B),若不聯通,你的程序需要輸出”impossible”。
Input
第一行一個正整數N,表示冰島的數量。
第二行N個範圍[0, 1000]的整數,爲每座島嶼初始的帝企鵝數量。
第三行一個正整數M,表示命令的數量。
接下來M行即命令,爲題目描述所示。
Output
對於每個bridge命令與excursion命令,輸出一行,爲題目描述所示。
Sample Input
5
4 2 4 5 6
10
excursion 1 1
excursion 1 2
bridge 1 2
excursion 1 2
bridge 3 4
bridge 3 5
excursion 4 5
bridge 1 3
excursion 2 4
excursion 2 5
Sample Output
4
impossible
yes
6
yes
yes
15
yes
15
16
HINT
1<=N<=30000
1<=M<=100000
LCT模板題。。
1A。。
雙倍經驗題。。
附上本蒟蒻的代碼:
#include<cstdio>
#include<iostream>
using namespace std;
int n,m,father[30001],c[30001][2],st[30001],sum[30001],val[30001];
bool rev[30001];
int read()
{
int w=0,f=1; char ch=getchar();
while (ch<'0' || ch>'9')
{
if (ch=='-') f=-1;
ch=getchar();
}
while (ch>='0' && ch<='9')
w=w*10+ch-'0',ch=getchar();
return w*f;
}
bool isroot(int x)
{
return c[father[x]][0]!=x && c[father[x]][1]!=x;
}
void update(int x)
{
int l=c[x][0],r=c[x][1];
sum[x]=sum[l]+sum[r]+val[x];
}
void pushdown(int x)
{
int l=c[x][0],r=c[x][1];
if (rev[x]) rev[x]^=1,rev[l]^=1,rev[r]^=1,swap(c[x][0],c[x][1]);
}
void rotate(int x)
{
int y=father[x],z=father[y],l,r;
if (c[y][0]==x) l=0;
else l=1;
r=l^1;
if (!isroot(y))
if (c[z][0]==y) c[z][0]=x;
else c[z][1]=x;
father[x]=z,father[y]=x,father[c[x][r]]=y,c[y][l]=c[x][r],c[x][r]=y,update(y),update(x);
}
void splay(int x)
{
int i,top=0,y,z;
st[++top]=x;
for (i=x;!isroot(i);i=father[i]) st[++top]=father[i];
for (i=top;i;i--) pushdown(st[i]);
while (!isroot(x))
{
y=father[x],z=father[y];
if (!isroot(y))
if (c[y][0]==x^c[z][0]==y) rotate(x);
else rotate(y);
rotate(x);
}
}
void access(int x)
{
int t;
for (t=0;x;t=x,x=father[x]) splay(x),c[x][1]=t,update(x);
}
void rever(int x)
{
access(x),splay(x),rev[x]^=1;
}
void link(int x,int y)
{
rever(x),father[x]=y;
}
int find(int x)
{
int y=x;
access(x),splay(x);
while (c[y][0]) y=c[y][0];
return y;
}
int main()
{
int i,x,y;
char s[20];
n=read();
for (i=1;i<=n;i++) sum[i]=val[i]=read();
m=read();
for (i=1;i<=m;i++)
{
scanf("%s",&s),x=read(),y=read();
if (s[0]=='b')
if (find(x)!=find(y)) printf("yes\n"),link(x,y);
else printf("no\n");
if (s[0]=='p')
rever(x),val[x]=y,update(x);
if (s[0]=='e')
if (find(x)!=find(y)) printf("impossible\n");
else rever(x),access(y),splay(y),printf("%d\n",sum[y]);
}
return 0;
}