题目地址 :
http://acm.hdu.edu.cn/showproblem.php?pid=1698
题目描述 :
1 10 2 1 5 2 5 9 3
Case 1: The total value of the hook is 24.
标准的线段树, 成段更新 ,...... 具体看 代码 注释 .
代码如下 :
/*
Coded By : MiYu
Link : http://www.cnblogs.com/MiYu || http://www.cppblog.com/MiYu
Author By : MiYu
Test : 1
Program : 1698
*/
//#pragma warning( disable:4789 )
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#include <utility>
#include <queue>
#include <stack>
#include <list>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
typedef struct seg_tree{
int left, right, col;
bool cov; //标记当前线段是否被覆盖, 如果true, 表示这一段线段的值都为 col. false则相反
int mid (){ return (left + right) >> 1; }
}SEG;
SEG seg[300010];
void creat ( int beg, int end, int rt = 1 ){
seg[rt].left = beg;
seg[rt].right = end;
seg[rt].col = 1;
seg[rt].cov = true;
if ( beg == end ) return;
int mid = seg[rt].mid();
creat ( beg, mid, rt << 1 );
creat ( mid + 1, end, ( rt << 1 ) + 1 );
}
void modify ( int beg, int end, int val, int rt = 1 ){
int LL = rt << 1;
int RR = ( rt << 1 ) + 1;
if ( seg[rt].left == beg && seg[rt].right == end ){ //线段被覆盖, 标记 cov 为true
seg[rt].cov = true;
seg[rt].col = val;
return ;
}
if ( seg[rt].cov ){ //如果线段曾经被覆盖, 标记 false, 将col往下传
seg[rt].cov = false;
seg[LL].col = seg[RR].col = seg[rt].col;
seg[LL].cov = seg[RR].cov = true;
}
int mid = seg[rt].mid();
if ( end <= mid ){
modify ( beg, end, val, LL );
} else if ( beg > mid ) {
modify ( beg, end, val, RR );
} else {
modify ( beg, mid, val, LL );
modify ( mid + 1, end, val, RR );
}
}
int quy ( int beg, int end, int rt = 1 ){
if ( seg[rt].cov ){ // 线段如果是被覆盖的 , 直接返回这一段区间的值
return ( seg[rt].right - seg[rt].left + 1 ) * seg[rt].col;
}
int mid = seg[rt].mid();
return quy ( beg, mid, rt << 1 ) + quy ( mid + 1, end, ( rt << 1 ) + 1 );
}
int main ()
{
int T, ca = 1;
scanf ( "%d", &T );
while ( T -- ){
int N;
scanf ( "%d", &N );
creat ( 1, N );
int M;
scanf ( "%d", &M );
for ( int i = 1; i <= M; ++ i ){
int beg, end, val;
scanf ( "%d%d%d", &beg, &end, &val );
modify ( beg, end, val );
}
printf ( "Case %d: The total value of the hook is %d.\n", ca++,quy( 1, N ) );
}
return 0;
}
/*
1
10
2
1 5 2
5 9 3
*/
/* 此为一牛人代码 , 速度 非常快 !!!! 0rz.........
#include<stdio.h>
int a[100001][3],c[100001];
int main()
{
int t,i,j,n,m,sum,v,w=1;
scanf("%d",&t);
while(t--&&scanf("%d %d",&n,&m))
{
sum=0;
for(i=1;i<=m;i++)
scanf("%d %d %d",&a[i][0],&a[i][1],&a[i][2]);
for(i=1;i<=n;i++)
{
v=1;
for(j=m;j>=1;j--)
{
if(a[j][0]<=i&&a[j][1]>=i)
{
v=a[j][2];
break;
}
}
sum+=v;
}
printf("Case %d: The total value of the hook is %d.\n",w++,sum);
}
}
*/