HLG 1041Chocolate Auction【并查集】

Description

In some cultural traditions, giving chocolate as a present on Valentine’s Day is a very traditional symbol of love. LDA does some research on chocolate manufacturing. And luckily, he makes some good quality chocolate bars. In addition, these chocolate bars are very long. They are composed of many identical small pieces. These pieces form into a straight line. For example, if a chocolate bar has 5 pieces, we can say its length is 5 units. From the first one to the last one, they are numbered as 1, 2, 3, 4 and 5, respectively.Then he holds an auction for his chocolate. In order to make this auction more interesting and lucrative, he invented a special way. Here is how he does: the chocolate bar is laid on the table. He cuts it M times in total. For theith time, he gives an interval [Ai, Bi], if any piece between Aiand Bi(Ai, Biincluded) hasn't been taken away yet, he will cut these pieces for sell, the others will remain on the table.

For example, there is a chocolate bar of length 6. Given the cutting interval [1, 2], the piece 1 and piece 2 will be cut off in the first time. For the 2nd time, the cutting interval is [4, 4], so the piece 4 will be cut off. The final cutting interval is [1, 3] which contains piece 1, 2, and 3. Since piece 1 and piece 2 have been already cut off, the 3rd piece is the last should be cut off.

 

Here comes the problem. You need to calculate how many pieces have been cut off and sold in each time. Since the chocolate bar can be very long and each chocolate bar will be cut in M times, any brute-force algorithm will fail to solve this problem.

Input

The first line is an integer T which is the number of the chocolate bars. Each chocolate is a test case, in which the first line includes two integer N, M (0 < N ≤ 1,000,000, 0 < M ≤ 100, 000). N is the length of the chocolate bar and M is the number of the times LDA will cut. Notice that after M rounds, the bar may still have some pieces left. And for each round, it is possible that no piece will be cut off. Then comes M lines. Each line contains two integers Ai, Bi(0 < Ai≤ Bi≤ N), which are the interval endpoints of theith cut.

Output

For each test case, output M lines, in which you are asked to represent the number of pieces cut off in each round.

Sample Input

1

6 4

1 2

4 4

1 3

1 4

Sample Output

2

1

1

0

code:

View Code
#include<stdio.h>
int a[10000001];
int find(int x)
{
int r=x;
while(a[r]!=r)
r=a[r];
int i=x;
int j;
while(i!=r)
{
j=a[i];
a[i]=r;
i=j;
}
return r;
}
void join(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
if(fx>fy)
a[fy]=fx;
else a[fx]=fy;
}
}
int main()
{
int t,n,m,p,q,sum,k,z,i;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n+1;i++)
a[i]=i;
while(m--)
{
sum=0;
scanf("%d%d",&p,&q);
k=p;
k=find(p);
while(k<=q)
{
sum++;
join(k,k+1);
k=find(k+1);
}
printf("%d\n",sum);
}
}
return 0;
}

 

posted @ 2012-03-15 23:24  'wind  阅读(167)  评论(0编辑  收藏  举报