题目大意:给你一个长度为n的数组a,定义区间[l,r]的val为区间内所有不同的数值之和。现在有m个询问,每次询问一个区间,问区间的val是多少。
思路:将所有的询问按照右端点排序。然后暴力枚举右区间,然后对之前出现过的val做一个标记即可,每次都更新这个标记就好了。 具体的和HDU 5869一样,只不过5869还要预处理,比较难
//看看会不会爆int!数组会不会少了一维! //取物问题一定要小心先手胜利的条件 #include <bits/stdc++.h> using namespace std; #define LL long long #define ALL(a) a.begin(), a.end() #define pb push_back #define mk make_pair #define fi first #define se second const int maxn = 50000 + 5; const int maxm = 200000 + 5; const int maxval = 1000000 + 5; LL tree[maxn], a[maxn], ans[maxm]; vector<pair<int, int> > q[maxn]; int n, m; int pre[maxval]; inline int lowbit(int x) {return x & -x;} void update(int x, int val){ for (int i = x; i <= n; i += lowbit(i)) tree[i] += val; } LL sum(int x){ LL ans = 0; for (int i = x; i > 0; i -= lowbit(i)){ ans += tree[i]; } return ans; } int main(){ int t; cin >> t; while (t--){ memset(pre, 0, sizeof(pre)); memset(tree, 0, sizeof(tree)); scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%I64d", a + i); q[i].clear(); } scanf("%d", &m); for (int i = 1; i <= m; i++){ int l, r; scanf("%d%d", &l ,&r); q[r].pb(mk(l, i)); } for (int i = 1; i <= n; i++){ if (pre[a[i]]){ update(pre[a[i]], -1 * a[i]); } pre[a[i]] = i; update(i, a[i]); int len = q[i].size(); for (int j = 0; j < len; j++){ pair<int, int> p = q[i][j]; ans[p.second] = sum(i) - sum(p.first - 1); } } for (int i = 1; i <= m; i++){ printf("%I64d\n", ans[i]); } } return 0; }
时间: 2024-10-10 22:38:09