Lyp的戰鬥記錄
問題描述
衆所周知,我們的lyp神犇外號叫Altman,的確,在另一個平行宇宙,lyp神犇就是一個——Altman。
有一天,lyp神犇遇到了另一個平行宇宙中的他,得知了在其他的宇宙中,Altman是存在的,那麼,怪獸也是存在的咯。
作爲一個有名的oier,lyp神犇想要統計一下各個宇宙中怪獸的戰鬥力,他發現,一些怪獸在不同的宇宙都出現過(!. !,難不成怪獸不穿越,算了,不管了),每一個Altman都提供給lyp一些信息,告訴他一個怪獸比另一個怪獸的戰鬥力大多少(這個數可以是負數)。
Altman神犇爲了給你以表現機會,將這些信息都給你,並會時不時地問你兩個怪獸之間誰更強。
假設Altman們提到了怪獸都按
Altman們的信息的格式是
其中
Lyp的詢問的格式是:
輸入格式
第
第
輸出格式
對於每一個詢問,用單獨一行回答。
樣例輸入
3 3
1 1 2 3
1 3 2 1
2 1 3
1
數據約定
Solution
帶權並查集。
Code
#include <iostream>
#include <cstdio>
#include <assert.h>
using namespace std;
int n,q;
int fa[30010][3];
int find(int x){
if(x==fa[x][0])return x;
int tmp=find(fa[x][0]);
fa[x][1]+=fa[fa[x][0]][1];
fa[x][0]=tmp;
return tmp;
}
int main(){
#ifndef DEBUG
freopen("lyp.in","r",stdin);
freopen("lyp.out","w",stdout);
#endif
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++){
fa[i][0]=i;
fa[i][1]=0;
}
for(int i=1,ss;i<=q;i++){
int x,y,z;
scanf("%d%d%d",&ss,&x,&y);
if(ss==1){
scanf("%d",&z);
int fy=find(y);
fa[fy][0]=x;
fa[fy][1]=z-fa[y][1];
}
else{
int fx=find(x),fy=find(y);
if(fx!=fy){
printf("0\n");
continue;
}
else{
if(fy==y){
if(fa[x][1]>0)printf("%d\n",y);
else if(fa[x][1]<0)printf("%d\n",x);
else printf("0\n");
continue;
}
if(fx==x){
if(fa[y][1]>0)printf("%d\n",x);
else if(fa[y][1]<0)printf("%d\n",y);
else printf("0\n");
continue;
}
if(fa[x][1]>0&&fa[y][1]<0)printf("%d\n",y);
else if(fa[x][1]<0&&fa[y][1]>0)printf("%d\n",x);
else if(fa[x][1]<fa[y][1])printf("%d\n",x);
else if(fa[x][1]>fa[y][1])printf("%d\n",y);
else printf("0\n");
}
}
}
return 0;
}