比赛 |
CSP2023-J模拟赛 |
评测结果 |
AAAAAAAAAA |
题目名称 |
新建题目 |
最终得分 |
100 |
用户昵称 |
liuyiche |
运行时间 |
5.031 s |
代码语言 |
C++ |
内存使用 |
3.70 MiB |
提交时间 |
2023-10-18 21:01:01 |
显示代码纯文本
#include<bits/stdc++.h>
using namespace std;
int n, ans = 0;
struct node
{
int dep;
int fa;
int w;
vector<int> son;
};
vector<node> v(2005);
int f[2005][20];
inline void buildtree(int step, int fa, int cnt)
{
v[step].dep = cnt;
v[step].fa = fa;
int del = -1;
for (int i = 0; i < v[step].son.size(); ++i)
{
if(v[step].son[i] == fa)
del = i;
else
buildtree(v[step].son[i],step,cnt+1);
}
if(del != -1)
v[step].son.erase(v[step].son.begin()+del);
}
inline void dfs(int u, int fa)
{
int num = v[u].son.size();
v[u].dep = v[fa].dep+1;
for (int i = 0; i <= log2(n); ++i)
f[u][i+1] = f[f[u][i]][i];
for (int i = 0; i < num; ++i)
{
int cd = v[u].son[i];
f[cd][0] = u;
dfs(cd,u);
}
}
inline int LCA(int x, int y)
{
if(v[x].dep < v[y].dep)
swap(x,y);
for (int i = log2(n); i >= 0; --i)
{
if(f[x][i] > 0 && v[f[x][i]].dep >= v[y].dep)
x = f[x][i];
if(x == y)
return x;
}
for (int i = log2(n); i >= 0; --i)
{
if(f[x][i] != f[y][i])
{
x = f[x][i];
y = f[y][i];
}
}
return f[x][0];
}
inline bool Ishigh(int x, int y, int z)
{
vector<int> l;
deque<int> q;
q.push_back(x);
l.push_back(x);
l.push_back(y);
while(q.front() != z)
{
int a = q.front();
q.pop_front();
q.push_back(v[a].fa);
l.push_back(q.front());
}
q.clear();
q.push_back(y);
while(q.front() != z)
{
int a = q.front();
q.pop_front();
q.push_back(v[a].fa);
l.push_back(q.front());
}
q.clear();
for (int i = 0; i < l.size(); ++i)
for (int j = i+1; j < l.size(); ++j)
{
int a = i, b = j;
if(v[l[a]].dep < v[l[b]].dep)
swap(a,b);
if(v[l[a]].dep > v[l[b]].dep && v[l[a]].w <= v[l[b]].w)
return false;
}
return true;
}
int main()
{
freopen("touch.in", "r", stdin);
freopen("touch.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> v[i].w;
for (int i = 1; i < n; ++i)
{
int x, y;
cin >> x >> y;
v[x].son.push_back(y);
v[y].son.push_back(x);
}
buildtree(1,0,1);
dfs(1,0);
//cout << '\n';
for (int i = 1; i <= n; ++i)
for (int j = i+1; j <= n; ++j)
{
int id = LCA(i,j);
if(Ishigh(i,j,id) == true)
{
ans++;
//cout << i << " " << j << " " << id << '\n';
}
}
cout << ans;
return 0;
}