题目大意:
就是现在给出一个有N个结点的树(N <= 100000)编号从1到N, 树的根节点为1, 给定K, 每个点都有一个权值, 权值0 <= wi <= 10^9, 现在有Q次询问, 对于每次询问给出一个x代表询问在编号x的结点及其子树中, 出现恰好K次的取值有多少种?
大致思路:
第一次写莫队算法.....
对于静态的满足能在O(1)的时间把[L, R]的答案转移到[L, R + 1], [L - 1, R]的问题, 可以考虑莫队算法, 这题先将N个结点的后序遍历顺序处理出来, 那么每次询问就相当于在这个数列中询问连续的一段中恰好出现K次的数的种数, 于是先将权值离散化然后就可以计数了
将Q次询问离线出来分块, 按照右端点递增排序, 根据莫队算法, 复杂度在O(Nsqrt(N))级别
代码如下:
Result : Accepted Memory : 10928 KB Time : 1279 ms
/*
* Author: Gatevin
* Created Time: 2015/8/2 18:52:13
* File Name: Sakura_Chiyo.cpp
*/
#pragma comment(linker, "/STACK:16777216")
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;
#define maxn 100100
int N, K, Q;
vector<int> V;
int w[maxn];
int L[maxn], R[maxn];
int tim;
vector<int> G[maxn];
int ans;
struct Ask
{
int l, r, pos, id;
Ask(int _l, int _r, int _pos, int _id) : l(_l), r(_r), pos(_pos), id(_id){}
Ask(){}
};
bool cmp(Ask a1, Ask a2)
{
return a1.pos < a2.pos || (a1.pos == a2.pos && a1.r < a2.r);
}
Ask ask[maxn];
void dfs(int now, int fa)
{
L[now] = ++tim;
for(int i = 0, sz = G[now].size(); i < sz; i++) if(G[now][i] != fa)
dfs(G[now][i], now);
R[now] = tim;
return;
}
int result[maxn];
int sum[maxn];
void add(int w)
{
if(sum[w] == K) ans--;
sum[w]++;
if(sum[w] == K) ans++;
return;
}
void del(int w)
{
if(sum[w] == K) ans--;
sum[w]--;
if(sum[w] == K) ans++;
return;
}
int main()
{
int T;
scanf("%d", &T);
for(int cas = 1; cas <= T; cas++)
{
scanf("%d %d", &N, &K);
V.clear();
for(int i = 1; i <= N; i++)
{
scanf("%d", w + i);
V.push_back(w[i]);
}
sort(V.begin(), V.end());
for(int i = 1; i <= N; i++)
w[i] = lower_bound(V.begin(), V.end(), w[i]) - V.begin();//离散化
int u, v;
for(int i = 1; i <= N; i++) G[i].clear();
for(int i = 1; i < N; i++)
{
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
tim = 0;
dfs(1, -1);//处理出时间戳, 实际上也就是树的后续遍历的顺序
scanf("%d", &Q);
int x;
int siz = sqrt(N*1.) + 4;
for(int i = 0; i < Q; i++)
{
scanf("%d", &x);
ask[i].l = L[x], ask[i].r = R[x];
ask[i].pos = L[x] / siz, ask[i].id = i;
}
sort(ask, ask + Q, cmp);
printf("Case #%d:\n", cas);
memset(sum, 0, sizeof(sum));
int l = 1, r = 0;
ans = 0;
add(w[++r]);
for(int i = 0; i < Q; i++)
{
while(r < ask[i].r) add(w[++r]);
while(r > ask[i].r) del(w[r--]);
while(l < ask[i].l) del(w[l++]);
while(l > ask[i].l) add(w[--l]);
result[ask[i].id] = ans;
}
for(int i = 0; i < Q; i++)
printf("%d\n", result[i]);
if(cas != T) puts("");
}
return 0;
}