题目链接

分析:树上的节点祖先与儿子的关系,一般就会想到dfs序。正解就是对树先进行dfs序排列,再将问题转化到树状数组统计个数。应该把节点按照权值从大到小排序,这样对于a[i],K/a[i]就是从小到大的顺序。这样更新树状数组就不会造成计算的混乱了。

多组数据没有每次先清除边我真是太智障了。

代码:

/*****************************************************/
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <map>
#include <set>
#include <ctime>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define offcin ios::sync_with_stdio(false)
#define sigma_size 26
#define lson l,m,v<<1
#define rson m+1,r,v<<1|1
#define slch v<<1
#define srch v<<1|1
#define sgetmid int m = (l+r)>>1
#define LL long long
#define ull unsigned long long
#define mem(x,v) memset(x,v,sizeof(x))
#define lowbit(x) (x&-x)
#define bits(a) __builtin_popcount(a)
#define mk make_pair
#define pb push_back
#define fi first
#define se second const int INF = 0x3f3f3f3f;
const LL INFF = 1e18;
const double pi = acos(-1.0);
const double inf = 1e18;
const double eps = 1e-9;
const LL mod = 1e9+7;
const int maxmat = 10;
const ull BASE = 31; /*****************************************************/ const int maxn = 1e5 + 5;
int in[maxn], out[maxn], dfs_clock;
int a[maxn], outdgree[maxn];
int sum[maxn];
std::vector<int> G[maxn];
int N;
LL K;
struct Node {
int val, id;
bool operator <(const Node &rhs) const {
return val < rhs.val;
}
}node[maxn];
void init() {
mem(sum, 0);
mem(node, 0);
mem(in, 0);
mem(out, 0);
mem(outdgree, 0);
dfs_clock = 0;
}
void dfs(int u, int fa) {
if (in[u]) return;
in[u] = ++ dfs_clock;
for (int i = 0; i < G[u].size(); i ++) {
int v = G[u][i];
if (v == fa) continue;
dfs(v, u);
}
out[u] = dfs_clock;
}
void add(int x) {
while (x <= N) {
sum[x] ++;
x += lowbit(x);
}
}
int query(int x) {
int res = 0;
while (x) {
res += sum[x];
x -= lowbit(x);
}
return res;
}
int main(int argc, char const *argv[]) {
int T;
cin>>T;
while (T --) {
init();
scanf("%d%I64d", &N, &K);
for (int i = 1; i <= N; i ++) G[i].clear();
for (int i = 1; i <= N; i ++) {
scanf("%d", &node[i].val);
node[i].id = i;
}
for (int i = 0; i < N - 1; i ++) {
int u, v;
scanf("%d%d", &u, &v);
outdgree[v] ++;
G[u].pb(v);
G[v].pb(u);
}
sort(node + 1, node + N + 1);
int root = 1;
for (int i = 1; i <= N; i ++) if (!outdgree[i]) {
root = i;
break;
}
dfs(root, -1);
int pos = 1;
LL ans = 0;
for (int i = N; i >= 1; i --) {
LL tmp = K / (LL)node[i].val;
int id = node[i].id;
while (node[pos].val <= tmp && pos <= N)
add(in[node[pos ++].id]);
ans += query(out[id]) - query(in[id]);
}
cout<<ans<<endl;
}
return 0;
}
05-02 14:57
查看更多