Title effect: some beads necklace. Beads have different colors. We asked several times how many different colors had been in a certain range.
Thinking: This problem has taught me to learn smart offline practices. Sort the problem by the left endpoint. The processed position is the first occurrence of each color. Where the next occurrence of each color is. Then, 1 to the CNT cycle, where there is a problem with the left endpoint is the current node, just deal with his answer. The method is a prefix and can be used in a tree-like array. Then put the next occurrence of this color in position +1.
This avoids a color being processed two times in the query.
CODE:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAX 1000010using namespace std;struct complex{int x,y,_id; BOOL operator < (const Complex &a) Const {return x < a.x; } void Read () {scanf ("%d%d", &x,&y); }}ask[max];int cnt,src[max],asks;int ans[max];int tree[max];int _next[max],last_color[max];void Fix (int x); int GetSum (int x); int main () {CIN >> cnt; for (int i = 1;i <= cnt; ++i) scanf ("%d", &src[i]); Cin >> asks; for (int i = 1;i <= asks; ++i) {ask[i]. Read (); ask[i]._id = i; } sort (ask + 1,ask + asks + 1); Fix (i) for (int i = 1;i <= cnt; ++i) {if (!last_color[src[i]]); _next[last_color[src[i]] = i; Last_color[src[i]] = i; } int p_ask = 1; for (int i = 1;i <= cnt, ++i) {while (ask[p_ask].x = = i) {ans[ask[p_ask]._id] = getsum (ask[p_ask].y)-getsum (ask[p_ask].x-1); p_ask++; } if (_next[i]) Fix (_next[i]); } for (int i = 1;i <= asks; ++i) printf ("%d\n", Ans[i]); return 0;} void Fix (int x) {for (int i = x;i <= cnt;i + = i&-i) tree[i]++;} int getsum (int x) {int re = 0; for (int i = x;i > 0;i-= i&-i) Re + = Tree[i]; return re;}
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Bzoj 1878 sdoi hh Necklace tree array + offline processing