题目:http://acm.hdu.edu.cn/showproblem.php?pid=1698 题意:屠夫的钩子由等长的金属材料构成(1~N),每段的值为1,2或3,改变x~y之间的值,最后输出总和#include <stdio.h> const int maxn=100000; struct SegmentTree { int l, r, lazy, sum; }st[maxn<<2]; int t, n, q, x, y, z, cnt; void BuildTree(int v, int left, int right) { st[v].l=left, st[v].r=right, st[v].lazy=1; if (st[v].l==st[v].r) { st[v].sum=1; return; } int lc=v<<1; int rc=lc+1; int mid=(left+right)>>1; BuildTree(lc, left, mid); BuildTree(rc, mid+1, right); st[v].sum=st[lc].sum+st[rc].sum; } void Insert(int left, int right, int v, int w) { if (st[v].lazy==w) return; if (st[v].l==left&&st[v].r==right) { st[v].lazy=w; st[v].sum=(right-left+1)*w; return; } int lc=v<<1; int rc=lc+1; if (st[v].lazy!=-1) { st[lc].lazy=st[v].lazy, st[rc].lazy=st[v].lazy; st[lc].sum=(st[lc].r-st[lc].l+1)*st[lc].lazy; st[rc].sum=(st[rc].r-st[rc].l+1)*st[rc].lazy; st[v].lazy=-1; } int mid=(st[v].l+st[v].r)>>1; if (left>mid) Insert(left, right, rc, w); else if (right<=mid) Insert(left, right, lc, w); else { Insert(left, mid, lc, w); Insert(mid+1, right, rc, w); } st[v].sum=st[lc].sum+st[rc].sum; } int main() { //freopen("in.txt", "r", stdin); scanf("%d", &t); cnt=1; while (t--) { scanf("%d", &n); BuildTree(1, 1, n); scanf("%d", &q); for (int i=0; i<q; i++) { scanf("%d %d %d", &x, &y, &z); Insert(x, y, 1, z); } printf("Case %d: The total value of the hook is %d.\n", cnt++, st[1].sum); } }
HDU 1698 Just a Hook
HDU 1698 屠夫的钩子解析
最新推荐文章于 2022-04-01 12:15:40 发布
本文介绍了一道名为“屠夫的钩子”的编程题,该题要求通过区间更新操作修改钩子各段的值,并最终计算总和。文章详细展示了如何使用线段树实现高效区间更新与查询,包括线段树的构建、区间更新的具体实现。

152

被折叠的 条评论
为什么被折叠?



