hrbust1041 并查集
感觉这道题用并查集用的挺巧妙的~链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1041
题意:
1,2,3,4,5,6……n块巧克力(不超过10^6),m次询问,每次询问问(a,b)之间还有几个巧克力,有几个吃掉几个。
例如样例:
sample intput
6 4
1 2
4 4
1 3
1 4
sample output
2
1
1
0
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #include <iostream> 4 #include <cstring> 5 #include <math.h> 6 using namespace std; 7 int father[1000010]; 8 int find(int x){ 9 if(x!=father[x]) 10 father[x]=find(father[x]); 11 return father[x]; 12 } 13 int main(){ 14 int T,i,j; 15 int n,m; 16 int a,b; 17 scanf("%d",&T); 18 while(T--){ 19 scanf("%d%d",&n,&m); 20 for(i=1;i<=n+1;i++) father[i]=i; 21 for(i=0;i<m;i++){ 22 scanf("%d %d",&a,&b); 23 int fb=find(b+1); 24 int ans=0; 25 for(j=a;j<=b;){ 26 int fj=find(j); 27 if(fj!=j) j=fj; 28 else { 29 ans++; 30 j++; 31 father[fj]=fb; 32 } 33 } 34 printf("%d\n",ans); 35 } 36 } 37 return 0; 38 }