[BZOJ4378][POI2015]Logistyka(樹狀陣列)
阿新 • • 發佈:2018-11-23
Address
Solution
顯然我們的重點在詢問。(廢話)
先說結論:
設數集中
的數有
個。
每次選
個正數減一這種操作能進行
次,當且僅當
(1)
,
或者(2)數集中
的數之和
。
證明:
(1)當
時顯然。只需要每次操作都對這
個數執行即可。
(2)
必要性:相當於在
的數中每次選
個數減一,進行
次操作。如果
的數之和小於
,則顯然是不行的。
充分性:可以使用數學歸納法證明:一個數集,裡面的數和為
,每次選
個數減一,可以使所有數變成
的充分必要條件是數集裡每個數都不超過
。使用這個結論就能推出數集中
的數之和
時一定能做到。
於是我們可以將運算元離散化,使用樹狀陣列維護每個數值的出現次數和出現的數之和。
這樣我們就能方便地在支援修改的情況下求
以及數集中
的數之和了。
時間複雜度
。
Code
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define For(i, a, b) for (i = a; i <= b; i++)
#define Bitr(x, n) for (; x <= n; x += x & -x)
#define Bitl(x) for (; x; x -= x & -x)
inline int read()
{
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
inline char get()
{
char c;
while ((c = getchar()) != 'U' && c != 'Z');
return c;
}
typedef long long ll;
const int N = 1e6 + 5;
int n, m, a[N], X[N], Y[N], tm, ttm, b[N], A[N];
char op[N];
ll sum, Asum[N];
void change(int x, int v)
{
Bitr(x, ttm) A[x] += v;
}
void changes(int x, int v)
{
Bitr(x, ttm) Asum[x] += v;
}
int ask(int x)
{
int res = 0;
Bitl(x) res += A[x];
return res;
}
ll asks(int x)
{
ll res = 0;
Bitl(x) res += Asum[x];
return res;
}
int main()
{
int i;
n = read(); m = read();
b[tm = 1] = 0;
For (i, 1, m)
{
op[i] = get();
X[i] = read(); Y[i] = read();
b[++tm] = Y[i];
}
std::sort(b + 1, b + tm + 1);
ttm = std::unique(b + 1, b + tm + 1) - b - 1;
For (i, 1, m) Y[i] = std::lower_bound(b + 1, b + ttm + 1, Y[i]) - b;
For (i, 1, n) change(a[i] = 1, 1);
For (i, 1, m)
if (op[i] == 'U')
{
sum += b[Y[i]] - b[a[X[i]]];
change(a[X[i]], -1); change(Y[i], 1);
changes(a[X[i]], -b[a[X[i]]]);
changes(Y[i], b[Y[i]]);
a[X[i]] = Y[i];
}
else
{
int xcnt = n - ask(Y[i] - 1);
ll xsum = asks(Y[i] - 1);
puts(xcnt >= X[i] || xsum >= 1ll * (X[i] - xcnt) * b[Y[i]]
? "TAK" : "NIE");
}
return 0;
}