POJ2777(线段树)

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值