程序员人生 网站导航

UVA12086 - Potentiometer(线段树/树状数组)

栏目:互联网时间:2014-10-08 08:07:47

UVA12086 - Potentiometer(线段树/树状数组)

题目链接

题目大意:给你N个数字,然后有q个操作,操作类型:M代表修改某个位置的值为r,S代表查询某一段的数字和。

解题思路:线段树或者树状数组。

线段树

#include <cstdio> #include <cstring> const int N = 8e5 + 5; int v[N]; int n; int Query (int o, int l, int r, int ql, int qr) { int m = l + (r - l) / 2; if (ql == l && r == qr) return v[o]; if (qr <= m) return Query(2 * o, l, m, ql, qr); else if (ql > m) return Query(2 * o + 1, m + 1, r, ql, qr); else return Query(2 * o, l, m, ql, m) + Query(2 * o + 1, m + 1, r, m + 1, qr); } void Update (int o, int l, int r, int p, int val) { int m = l + (r - l) / 2; if (l == r) v[o] = val; else { if (p <= m) Update (2 * o, l, m, p, val); else Update (2 * o + 1, m + 1, r, p, val); v[o] = v[2 * o] + v[2 * o + 1]; } } void solve () { char str[10]; int x, y, r; while (scanf ("%s", str) && str[0] != 'E') { if (str[0] == 'M') { scanf ("%d%d", &x, &y); printf ("%d ", Query (1, 1, n, x, y)); } else { scanf ("%d%d", &x, &r); Update (1, 1, n, x, r); } } } int main () { int cas = 0; int num; while (scanf ("%d", &n) && n) { if (cas) printf (" "); printf ("Case %d: ", ++cas); memset (v, 0, sizeof (v)); for (int i = 1; i <= n; i++) { scanf ("%d", &num); Update (1, 1, n, i, num); } solve(); } return 0; }

树状数组

#include <cstdio> #include <cstring> const int maxn = 2e5 + 5; int lowbit (int x) { return x&-x; } int n; int A[maxn], C[maxn]; void Add (int x, int d) { while (x <= n) { C[x] += d; x += lowbit(x); } } int Sum (int x) { int ret = 0; while (x > 0) { ret += C[x]; x -= lowbit(x); } return ret; } void solve () { char str[10]; int x, r, y; while (scanf ("%s", str) && str[0] != 'E') { if (str[0] == 'M') { scanf ("%d%d", &x, &y); printf ("%d ", Sum (y) - Sum (x - 1)); } else { scanf ("%d%d", &x, &r); Add(x, r - A[x]); A[x] = r;//这个地方要记得修改 } } } int main () { int cas = 0; while (scanf ("%d", &n) && n) { if (cas) printf (" "); memset (C, 0, sizeof (C)); for (int i = 1; i <= n; i++) { scanf ("%d", &A[i]); Add(i, A[i]); } printf ("Case %d: ", ++cas); solve(); } return 0; }
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐