不久之前,Mirko建立了一个旅行社,名叫“极地之梦”。这家旅行社在北极附近购买了N座冰岛,并且提供观光服务。
当地最受欢迎的当然是帝企鹅了,这些小家伙经常成群结队的游走在各个冰岛之间。Mirko的旅行社遭受一次重大打击,以至于观光游轮已经不划算了。旅行社将在冰岛之间建造大桥,并用观光巴士来运载游客。
Mirko希望开发一个电脑程序来管理这些大桥的建造过程,以免有不可预料的错误发生。这些冰岛从1到N标号。一开始时这些岛屿没有大桥连接,并且所有岛上的帝企鹅数量都是知道的。每座岛上的企鹅数量虽然会有所改变,但是始终在[0, 1000]之间。你的程序需要处理以下三种命令:
bridge A B:询问结点A与结点B是否连通。如果是则输出“no”。否则输出“yes”,并且在结点A和结点B之间连一条无向边。penguins A X:将结点A对应的权值wA修改为X。excursion A B:如果结点A和结点B不连通,则输出“impossible”。否则输出结点A到结点B的路径上的点对应的权值的和。给出q个操作,要求在线处理所有操作。
输入格式:
第一行包含一个整数n(1<=n<=30000),表示节点的数目。
第二行包含n个整数,第i个整数表示第i个节点初始时对应的权值。
第三行包含一个整数q(1<=n<=300000),表示操作的数目。
以下q行,每行包含一个操作,操作的类别见题目描述。
任意时刻每个节点对应的权值都是1到1000的整数。
输出格式:
输出所有bridge操作和excursion操作对应的输出,每个一行。
输入样例#1:
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输出样例#1:
4 impossible yes 6 yes yes 15 yes 15 16数据范围:1<=n<=30000, 1<=q<=300000, 0<=wi<=1000。
题意:
Link,单点修改,路径查询
#include<bits/stdc++.h> #define N 30005 #define lc t[x].ch[0] #define rc t[x].ch[1] using namespace std; int n,q,a[N]; char s[20]; struct Node{ int ch[2],fa,tag,val; }t[N]; int read(){ int cnt=0,f=1;char ch=0; while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar(); return cnt*f; } bool isRoot(int x){ int fa=t[x].fa; if(fa==0) return true; return t[fa].ch[0]!=x && t[fa].ch[1]!=x; } void Pushup(int x){ t[x].val = t[lc].val + t[rc].val + a[x]; } void Pushdown(int x){ if(t[x].tag){ swap(lc,rc); t[lc].tag^=1,t[rc].tag^=1; t[x].tag=0; } } void Pushpath(int x){ if(!isRoot(x)) Pushpath(t[x].fa); Pushdown(x); } void rotate(int x){ int y=t[x].fa,z=t[y].fa; int k=t[y].ch[1]==x; if(!isRoot(y)) t[z].ch[t[z].ch[1]==y]=x; t[x].fa=z; t[y].ch[k]=t[x].ch[k^1]; t[t[x].ch[k^1]].fa=y; t[x].ch[k^1]=y,t[y].fa=x; Pushup(y),Pushup(x); } void Splay(int x){ Pushpath(x); while(!isRoot(x)){ int y=t[x].fa,z=t[y].fa; if(!isRoot(y)) (t[y].ch[0]==x)^(t[z].ch[0]==y) ? rotate(x) : rotate(y); rotate(x); } } void Access(int x){ for(int y=0;x;y=x,x=t[x].fa) Splay(x),rc=y,Pushup(x); } void Makeroot(int x){ Access(x),Splay(x),t[x].tag^=1; } int Findroot(int x){ Access(x),Splay(x); while(lc) Pushdown(x),x=lc; return x; } void Link(int x,int y){ Makeroot(x),t[x].fa=y; } int main(){ //freopen("1.in","r",stdin); n=read(); for(int i=1;i<=n;i++) a[i]=read(); q=read(); while(q--){ scanf("%s",s);int x=read(),y=read(); if(s[0]=='e'){ Makeroot(x); if(Findroot(y)==x){Access(y),Splay(y);printf("%d\n",t[y].val);} else printf("impossible\n"); } if(s[0]=='p'){ Access(x),Splay(x),a[x]=y,Pushup(x); } if(s[0]=='b'){ if(Findroot(x)==Findroot(y)) printf("no\n"); else Link(x,y),printf("yes\n"); } } }
