#include "iostream"
using namespace std;
struct Node
{
int left;
int right;
int mid;
int value;
};
Node Tree[300000];
void BuildTree(int level, int left, int right)
{
Tree[level].value = 1;
Tree[level].left = left;
Tree[level].right = right;
Tree[level].mid = (left+right)/2;
if(left==right)
return;
else
{
BuildTree(2*level, left, Tree[level].mid);
BuildTree(2*level+1, Tree[level].mid+1, right);
}
}
void Insert(int level, int left, int right, int value)
{
if(left==Tree[level].left && right==Tree[level].right)
{
Tree[level].value = value;
return;
}
if(Tree[level].value != 0) //这个if语句的作用就是将value下移,并将无效的区间段置0
{
Tree[2*level].value = Tree[level].value;
Tree[2*level+1].value = Tree[level].value;
Tree[level].value = 0;
}
if(left > Tree[level].mid)
Insert(2*level+1, left, right, value);
else if(right <= Tree[level].mid)
Insert(2*level, left, right, value);
else
{
Insert(2*level, left, Tree[level].mid, value);
Insert(2*level+1, Tree[level].mid+1, right, value);
}
}
int SumUp(int level, int left, int right)
{
if(Tree[level].value > 0)
{
//cout<<" "<<Tree[level].left<<" "<<Tree[level].right<<" "<<Tree[level].value<<endl;
//上面这个句子用来看看哪些是有效的区间段
return Tree[level].value*(Tree[level].right-Tree[level].left+1);
}
if(left > Tree[level].mid)
SumUp(2*level+1, left, right);
else if(right <= Tree[level].mid)
SumUp(2*level, left, right);
else
return SumUp(2*level, left, Tree[level].mid)+SumUp(2*level+1, Tree[level].mid, right);
//累加的功能是在上面的这个return语句实现的,这个就是递归的妙处了。
}
int main()
{
int Case, lenofline, numofoper, left, right, value;
while(cin>>Case)
{
for(int i=1; i<=Case; i++)
{
cin>>lenofline>>numofoper;
BuildTree(1, 1, lenofline);
while(numofoper--)
{
cin>>left>>right>>value;
Insert(1, left, right, value);
}
cout<<"Case "<<i<<": The total value of the hook is "<<SumUp(1, 1, lenofline)<<"."<<endl;
}
}
}
Find函数的另外一种写法,用来统计经过点的所有次数
int Find(int level, int target)
{
if(target==Tree[level].left && target==Tree[level].right)
return Tree[level].icount;
else if(target > Tree[level].mid)
return Tree[levle].icount+Find(2*level+1, target);
else if(target <= Tree[level].mid)
return Tree[level].icount+Find(2*level, target);
}