[HEOI2012]采花
2743: [HEOI2012]采花
Time Limit: 15 Sec Memory Limit: 128 MBSubmit: 356 Solved: 153
[Submit][Status][Discuss]
Description
萧芸斓是Z国的公主,平时的一大爱好是采花。
今天天气晴朗,阳光明媚,公主清晨便去了皇宫中新建的花园采花。花园足够大,容纳了n朵花,花有c种颜色(用整数1-c表示),且花是排成一排的,以便于公主采花。公主每次采花后会统计采到的花的颜色数,颜色数越多她会越高兴!同时,她有一癖好,她不允许最后自己采到的花中,某一颜色的花只有一朵。为此,公主每采一朵花,要么此前已采到此颜色的花,要么有相当正确的直觉告诉她,她必能再次采到此颜色的花。由于时间关系,公主只能走过花园连续的一段进行采花,便让女仆福涵洁安排行程。福涵洁综合各种因素拟定了m个行程,然后一一向你询问公主能采到多少朵花(她知道你是编程高手,定能快速给出答案!),最后会选择令公主最高兴的行程(为了拿到更多奖金!)。
Input
第一行四个空格隔开的整数n、c以及m。接下来一行n个空格隔开的整数,每个数在[1, c]间,第i个数表示第i朵花的颜色。接下来m行每行两个空格隔开的整数l和r(l ≤ r),表示女仆安排的行程为公主经过第l到第r朵花进行采花。
Output
共m行,每行一个整数,第i个数表示公主在女仆的第i个行程中能采到的花的颜色数。
Sample Input
5 3 5
1 2 2 3 1
1 5
1 2
2 2
2 3
3 5
1 2 2 3 1
1 5
1 2
2 2
2 3
3 5
Sample Output
2
0
0
0
1
0
【样例说明】
询问[1, 5]:公主采颜色为1和2的花,由于颜色3的花只有一朵,公主不采;询问[1, 2]:颜色1和颜色2的花均只有一朵,公主不采;
询问[2, 2]:颜色2的花只有一朵,公主不采;
询问[2, 3]:由于颜色2的花有两朵,公主采颜色2的花;
询问[3, 5]:颜色1、2、3的花各一朵,公主不采。
【样例说明】
询问[1, 5]:公主采颜色为1和2的花,由于颜色3的花只有一朵,公主不采;询问[1, 2]:颜色1和颜色2的花均只有一朵,公主不采;
询问[2, 2]:颜色2的花只有一朵,公主不采;
询问[2, 3]:由于颜色2的花有两朵,公主采颜色2的花;
询问[3, 5]:颜色1、2、3的花各一朵,公主不采。
HINT
【数据范围】
对于100%的数据,1 ≤ n ≤ 10^6,c ≤ n,m ≤10^6。
Solution
树状数组, 离线修改。 按右端点排序
Code
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #ifdef unix 2 #define LLD "%lld" 3 #else 4 #define LLD "%I64d" 5 #endif 6 #include <cstdio> 7 #include <cstring> 8 #include <algorithm> 9 #include <iostream> 10 #include <cstdlib> 11 #include <cmath> 12 #include <queue> 13 #include <stack> 14 #define LL long long 15 #define maxn 2000100 16 #define INF 1 << 30 17 #define rep(i, j, k) for (int i = j; i <= k; i++) 18 #define For(i, j) for (int i = 1; i <= j; i++) 19 #define lson l, mid, rt << 1 20 #define rson mid + 1, r, rt << 1 | 1 21 using namespace std; 22 void file() { 23 freopen(".in", "r", stdin); 24 freopen(".out", "w", stdout); 25 } 26 int n, m, c, last[maxn], ans[maxn], pre[maxn], b[maxn]; 27 struct nod {int pos, l, r;}a[maxn]; 28 struct BIT { 29 inline int lowbit(int x) {return x & -x;} 30 inline void modify(int *a, int x, int data) {while (x <= n) a[x] += data, x+= lowbit(x);} 31 inline int sum(int *a, int x) { 32 int tot = 0; 33 while (x > 0) tot += a[x], x-=lowbit(x); 34 return tot; 35 } 36 }bit; 37 inline bool cmp(const nod &a, const nod &b) {return a.r < b.r;} 38 void init() { 39 scanf("%d%d%d", &n, &c, &m); 40 For(i, n) { 41 int x; 42 scanf("%d", &x); 43 pre[i] = last[x]; 44 last[x] = i; 45 } 46 For(i, m) 47 scanf("%d%d", &a[i].l, &a[i].r), a[i].pos = i; 48 sort(a + 1, a + 1 + m, cmp); 49 } 50 void work() { 51 int j = 1; 52 For(i, n) { 53 bit.modify(b, pre[pre[i]] + 1, 1), bit.modify(b, pre[i] + 1, -1); 54 while (j <= m && a[j].r == i) ans[a[j].pos] = bit.sum(b, a[j].l), ++j; 55 } 56 For(i, m) printf("%d\n", ans[i]); 57 } 58 int main() { 59 init(); 60 work(); 61 return 0; 62 }
I come, I see, I conquer!