Problem Description
TT and FF are … friends. Uh… very very good friends -__-b
FF is a bad boy, he is always wooing TT to play the following game with him. This is a very humdrum game. To begin with, TT should write down a sequence of integers-_-!!(bored).
Then, FF can choose a continuous subsequence from it(for example the subsequence from the third to the fifth integer inclusively). After that, FF will ask TT what the sum of the subsequence he chose is. The next, TT will answer FF’s question. Then, FF can redo this process. In the end, FF must work out the entire sequence of integers.
Boring~~Boring~~a very very boring game!!! TT doesn’t want to play with FF at all. To punish FF, she often tells FF the wrong answers on purpose.
The bad boy is not a fool man. FF detects some answers are incompatible. Of course, these contradictions make it difficult to calculate the sequence.
However, TT is a nice and lovely girl. She doesn’t have the heart to be hard on FF. To save time, she guarantees that the answers are all right if there is no logical mistakes indeed.
What’s more, if FF finds an answer to be wrong, he will ignore it when judging next answers.
But there will be so many questions that poor FF can’t make sure whether the current answer is right or wrong in a moment. So he decides to write a program to help him with this matter. The program will receive a series of questions from FF together with the answers FF has received from TT. The aim of this program is to find how many answers are wrong. Only by ignoring the wrong answers can FF work out the entire sequence of integers. Poor FF has no time to do this job. And now he is asking for your help~(Why asking trouble for himself~~Bad boy)
题解
并查集路径迭代的裸题,合并的时候注意一下顺序就好了。唯一要注意一点就是题目有多组数据(题目描述里没说啊!)
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 200006
using namespace std;
inline char nc(){
static char buf[100000],*i=buf,*j=buf;
return i==j&&(j=(i=buf)+fread(buf,1,100000,stdin),i==j)?EOF:*i++;
}
inline int _read(){
char ch=nc();int sum=0,op=1;
while(ch!=EOF&&ch!='-'&&!(ch>='0'&&ch<='9'))ch=nc();
if(ch==EOF)return -1e9;
if(ch=='-')op=-1,ch=nc();
while(ch>='0'&&ch<='9')sum=sum*10+ch-48,ch=nc();
return sum*op;
}
int n,m,ans,fa[maxn],dis[maxn];
int get(int x){
if(x==fa[x])return x;
int y=fa[x];
fa[x]=get(y);
dis[x]+=dis[y];
return fa[x];
}
void merge(int x,int y,int z){
int fy=get(y),fx=get(x);
if(fx==fy){if(z!=dis[y]-dis[x])ans++;}else
if(fx>fy){
fa[fx]=fy;dis[fx]=dis[y]-z-dis[x];
}else{
fa[fy]=fx;dis[fy]=dis[x]+z-dis[y];
}
}
int main(){
freopen("sequence.in","r",stdin);
freopen("sequence.out","w",stdout);
n=_read();m=_read();
while(n!=-1e9){
ans=0;
memset(dis,0,sizeof(dis));
for(int i=1;i<=n;i++)fa[i]=i;
while(m--){
int x=_read(),y=_read(),z=_read();
if(x>y)swap(x,y);
merge(x-1,y,z);
}
printf("%d\n",ans);
n=_read();m=_read();
}
return 0;
}