[NOIP模拟] 区间
2017.11.03 T1
Solution
很好我已经遇见两个作为 T1 比 T2 难的NOIP题,估计是自己太弱了。
对于每一个询问我们必须做到小于
O(n)
的复杂度才行,我们想想怎么做到,我们考虑打差分,比如对于询问 (x, y) , 我们对一个 x, 打+1,一个y,打-1,于是我们可以想到前面相同的 sum,可以组成一个平衡区间,于是我们就把x,y的位置提出来,x 和 y 的位置的个数
≤n
所以我们就得到小于
O(n)
的算法。
Code :
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <ctime>
#include <map>
#include <vector>
#define mp make_pair
using namespace std;
inline int read() {
int i = 0, f = 1;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') f = -1; ch = getchar();
}
while(isdigit(ch)) {
i = (i << 3) + (i << 1) + ch - '0'; ch = getchar();
}
return i * f;
}
const int MAXN = 8000 + 5;
int a[MAXN], b[MAXN], n, k, m, cnt[MAXN * 2], check[MAXN * 2];
map<int, int> num;
vector<int> p[MAXN];
map<pair<int, int>, int> ans;
inline void disc_init() {
sort(b + 1, b + n + 1);
m = unique(b + 1, b + n + 1) - b - 1;
for(int i = 1; i <= n; ++i)
a[i] = lower_bound(b + 1, b + m + 1, a[i]) - b, num[b[a[i]]] = a[i];
}
inline int solve(int x, int y, int l) {
int sum = n; check[sum] = l, cnt[sum] = 0; int pos = 0, tmp = 0;
int i = 0, j = 0, now = 0, mn = 0x3f3f3f3f, mx = (int)0xC0000000;
while(p[x][i] != n + 1 || p[y][j] != n + 1) {
if(p[x][i + 1] <= p[y][j + 1]) {
tmp += (cnt[sum] + cnt[sum] + p[x][i + 1] - pos - 1) * (p[x][i + 1] - pos) / 2;
cnt[sum] += p[x][i + 1] - pos;
pos = p[x][++i]; ++sum;
if(check[sum] != l) check[sum] = l, cnt[sum] = 0;
//printf("%d\n", cnt[sum - 1]);
}
else {
tmp += (cnt[sum] + cnt[sum] + p[y][j + 1] - pos - 1) * (p[y][j + 1] - pos) / 2;
cnt[sum] += p[y][j + 1] - pos;
pos = p[y][++j]; --sum;
if(check[sum] != l) check[sum] = l, cnt[sum] = 0;
//printf("%d\n", cnt[sum + 1]);
}
//printf("%d %d %d %d\n", pos, sum, p[x][i], p[y][j]);
}
//printf("mx = %d mn = %d\n", mx, mn);
ans[mp(x, y)] = tmp;
return tmp;
}
int main() {
//freopen("1.in", "r", stdin);
n = read(), k = read();
for(int i = 1; i <= n; ++i) a[i] = read(), b[i] = a[i];
disc_init();
for(int i = 0; i <= m; ++i) p[i].push_back(0);
for(int i = 1; i <= n; ++i) p[a[i]].push_back(i);
for(int i = 0; i <= m; ++i) p[i].push_back(n + 1), p[i].push_back(n + 2);
for(int i = 1; i <= k; ++i) {
int x = read(), y = read();
x = num[x], y = num[y];
if(x > y) swap(x, y);
int now = ans[mp(x, y)];
if(!now) cout<<solve(x, y, i)<<'\n';
else cout<<now<<'\n';
}
}