color为-1时表示这一段的区间内有不同的颜色,需要继续遍历其左子树和右子树。
线段树的构造用了如下所示的方式。
线段树相关知识:http://www.cnblogs.com/shuaiwhu/archive/2012/04/22/2464583.html
http://hi.baidu.com/semluhiigubbqvq/item/be736a33a8864789f4e4ad18
#include <iostream>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
struct Node
{
int left;
int right;
Node *leftchild;
Node *rightchild;
int color;
};
Node* build(int l,int r)
{
Node* root=new Node;
root->left=l;
root->right=r;
root->leftchild=NULL;
root->rightchild=NULL;
root->color=1;
if (l+1<r)
{
int mid=(r+l)>>1;
root->leftchild=build(l,mid);
root->rightchild=build(mid,r);
}
return root;
}
void Insert(int begin,int end,Node* root,int color)
{
if (begin<=root->left && end>=root->right)
{
if (root->color!=-1 && root->leftchild!=NULL && root->rightchild!=NULL)
{
root->leftchild->color=root->color;
root->rightchild->color=root->color;
}
root->color=color;
}
else
{
if (root->color!=-1 && root->leftchild!=NULL && root->rightchild!=NULL)
{
root->leftchild->color=root->color;
root->rightchild->color=root->color;
}
root->color=-1;
if (begin<(root->left+root->right)/2) Insert(begin,end,root->leftchild,color);
if (end>(root->left+root->right)/2) Insert(begin,end,root->rightchild,color);
}
}
int Traversal(int begin,int end,Node* root,int* record)
{
if (root->color!=-1)
{
if (record[root->color]==0)
{
record[root->color]=1;
return 1;
}
else
return 0;
}
else
{
if (begin<(root->left+root->right)/2 && end>(root->left+root->right)/2)
return Traversal(begin,end,root->leftchild,record)+Traversal(begin,end,root->rightchild,record);
else if (begin<(root->left+root->right)/2 && end<=(root->left+root->right)/2)
return Traversal(begin,end,root->leftchild,record);
else if (begin>=(root->left+root->right)/2 && end>(root->left+root->right)/2)
return Traversal(begin,end,root->rightchild,record);
else
return 0;
}
}
int main()
{
int L,T,O;
cin >> L >> T >> O;
getchar();
Node* root=build(1,L+1);
int i;
char c;
int begin;
int end;
int color;
int total=0;
for (i=1;i<=O;i++)
{
int record[31]={0};
scanf("%c",&c);
if (c=='C')
{
scanf("%d%d%d",&begin,&end,&color);
getchar();
Insert(begin,end+1,root,color);
}
else
{
scanf("%d%d",&begin,&end);
getchar();
total=Traversal(begin,end+1,root,record);
printf("%d\n",total);
}
}
return 0;
}