Code:
#include <bits/stdc++.h>
#define Maxsize 60000
using namespace std;
//线段树节点
struct node
{
int ld, rd; //左右孩子节点
int key; //标记值
} Tree[Maxsize * 2 + 1000];
//建树,i表示节点,a表示节点左右两边,从1开始建树
void buildtree(int i, int a, int b)
{
Tree[i].ld = a;
Tree[i].rd = b;
if (b - a == 1)
return;
buildtree(i * 2, a, (a + b) / 2);
buildtree(i * 2 + 1, (a + b) / 2, b);
return;
}
//插入
void insert(int i, int a, int b)
{
//没被完全覆盖
if (Tree[i].key == 0)
{
int m = (Tree[i].ld + Tree[i].rd) / 2;
//完全覆盖
if ((a == Tree[i].ld) && (b == Tree[i].rd))
{
Tree[i].key = 1;
return;
}
//如果在左子树
else if (b <= m)
insert(i * 2, a, b);
//如果在右子树
else if (a >= m)
insert(i * 2 + 1, a, b);
//如果横跨,则一分为二
else
{
insert(i * 2, a, m);
insert(i * 2 + 1, m, b);
}
}
}
//统计长度
int QLen(int i)
{
if (Tree[i].key == 1)
return Tree[i].rd - Tree[i].ld;
else if (Tree[i].rd - Tree[i].ld == 1)
return 0;
else
return QLen(i * 2) + QLen(i * 2 + 1);
}
int main()
{
int n;
while (cin >> n)
{
buildtree(1, 1, Maxsize);
int a, b;
for (int i = 0; i < n; i++)
{
cin >> a >> b;
insert(1, a, b);
}
cout << QLen(1);
}
return 0;
}