【HDU 3038】How Many Answers Are Wrong(带权并查集,区间型)

it2022-05-05  111

传送门 题意:给出区间[1,n],下面有m组数据。l r,v区间[l,r]之和为v,每输入一组数据,判断此组条件是否与前面冲突 ,如果此条件冲突,则忽视它,最后输出与前面冲突的数据的个数.

Solution: 带权并查集维护区间。 可以这么考虑,当几个区间能够拼起来的时,比如[1,3],[3,4],[4,7],我们就能确定[1,4],[4,7]的和。 观察就会发现,我们只需维护每个区间的边界能追溯到的祖先即可,比如7,它可以追溯到1。而当我们检查[l,r]的和时,只需先判断l与r是否拥有同一祖先,如果有的话,说明[l,r]的和是已经确定的,如果没有,则需要动态更新。

#include<bits/stdc++.h> #define N 200005 using namespace std; int n,m,father[N],sum[N],ans;//sum 到根节点的距离 inline int getfather(int x) { if(father[x]==x) return x; int fa=father[x]; father[x]=getfather(father[x]); sum[x]+=sum[fa]; return father[x]; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); while(cin>>n>>m) { ans=0; memset(sum,0,sizeof(sum)); for(int i=1;i<=N-2;i++) father[i]=i; for(int i=1;i<=m;i++) { int x,y,z; cin>>x>>y>>z; y++; int ax=getfather(x); int bx=getfather(y); if(ax==bx) { if(sum[x]+z!=sum[y]) { ans++; } } else { father[bx]=ax; sum[bx]=sum[x]+z-sum[y]; } } cout<<ans<<endl; } return 0; }

转载于:https://www.cnblogs.com/Patrickpwq/articles/9385670.html


最新回复(0)