MYF

HDU 5877 Weak Pair

题目链接

HDU 5877

题目类型:树状数组+dfs序

题目来源:2016 ACM/ICPC Asia Regional Dalian Online

题目分析

题目大意

给出一棵树的父子关系,问存在多少组点对(u, v),使两个节点的值的乘积小于等于k,并且保证uv的祖先

解析

对这棵树进行DFS,向下找到每个点的时候算与之前的节点总共能产生多少组合法点对即可,使用树状数组进行统计。

代码还是比较清晰优雅的

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <iomanip>
#include <bitset>
#include <cstring>
#include <iostream>
#include <iosfwd>
#include <deque>
#include <algorithm>
#define Memset(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)
#define PB push_back
#define MP make_pair
#define rt(n) (i == n ? '\n' : ' ')
#define hi printf("Hi----------\n")
#define IN freopen("input.txt","r",stdin);
#define OUT freopen("output.txt","w",stdout);
#define debug(x) cout<<"Debug : ---"<<x<<"---"<<endl;
#define debug2(x,y) cout<<"Debug : ---"<<x<<" , "<<y<<"---"<<endl;
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int maxn=100001+10;
const int mod=1000000007;
const int INF=0x3f3f3f3f;
const double eps=1e-8;
ll bin[maxn];
ll lowbit(ll x){
return x&(-x);
}
void update(ll pos, ll val){
while (pos<maxn) {
bin[pos]+=val;
pos += lowbit(pos);
}
}
ll sum (ll pos){
ll ret = 0;
while (pos > 0) {
ret += bin[pos];
pos -= lowbit(pos);
}
return ret;
}
ll a[maxn],tmp[maxn],b[maxn],ans,k,cnt;
int in[maxn];
vector<int> G[maxn];
void dfs(int u){
ll now = k / a[u]; //找到符合条件的上限
ll pos = upper_bound(tmp+1, tmp+1+cnt, now) - tmp; //找到第一个不符合条件的
ans += sum(pos-1);
update(b[u], 1);
for (int i = 0; i<G[u].size(); i++) {
dfs(G[u][i]); //向下DFS
}
update(b[u], -1);
}
void solve(){
// initialize
ans = 0;
memset(bin, 0, sizeof(bin));
memset(in, 0, sizeof(in));

// input and build tree
int n;
scanf("%d%lld",&n,&k);
for (int i = 1; i<=n; i++) {
scanf("%lld",&a[i]);
G[i].clear();
tmp[i] = a[i];
}
for (int i = 1; i<n; i++) {
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
in[v]++;
}

// 离散化
sort(tmp+1, tmp+1+n);
cnt = unique(tmp+1, tmp+1+n) - tmp - 1;
for (int i = 1; i<=n ; i++) {
b[i] = lower_bound(tmp+1, tmp+1+cnt, a[i]) - tmp;
}

// find root
int rt= 0;
for (int i = 1; i<=n; i++) {
if (in[i]==0) {
rt = i;
break;
}
}

// dfs
dfs(rt);

cout<<ans<<"\n";
}
int main(){
int T;
scanf("%d",&T);
while (T--) solve();
return 0;
}