# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
769136 | danikoynov | Cat Exercise (JOI23_ho_t4) | C++14 | 94 ms | 1040 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
void speed()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
const int maxn = 5010;
int n, a[maxn], used[maxn], dp[maxn], pos[maxn];
vector < int > adj[maxn];
int rec(int val)
{
if (used[val])
return dp[val];
used[val] = 1;
int left = 0, right = n + 1;
for (int i = n; i > val; i --)
{
if (pos[i] > pos[val])
{
right = min(right, pos[i]);
}
else
{
left = max(left, pos[i]);
}
}
int mx = -1;
for (int i = pos[val] + 1; i < right; i ++)
{
if (a[i] > mx)
{
mx = a[i];
dp[val] = max(dp[val], i - pos[val] + rec(a[i]));
}
}
mx = -1;
for (int i = pos[val] - 1; i > left; i --)
{
if (a[i] > mx)
{
mx = a[i];
dp[val] = max(dp[val], pos[val] - i + rec(a[i]));
}
}
return dp[val];
}
int dfs(int v, int p, int mx, int dis, int val)
{
if (mx > val)
return 0;
int ans = 0;
if (a[v] == mx)
ans = max(ans, dis + dp[v]);
for (int u : adj[v])
{
if (u == p)
continue;
ans = max(ans, dfs(u, v, max(mx, a[u]), dis + 1, val));
}
return ans;
}
void solve()
{
cin >> n;
for (int i = 1; i <= n; i ++)
{
cin >> a[i];
pos[a[i]] = i;
}
for (int i = 1; i < n; i ++)
{
int v, u;
cin >> v >> u;
adj[v].push_back(u);
adj[u].push_back(v);
}
for (int i = 1; i <= n; i ++)
{
int v = pos[i];
for (int u : adj[v])
{
dp[v] = max(dp[v], dfs(u, v, a[u], 1, a[v]));
}
///cout << v << " : " << dp[v] << endl;
}
cout << dp[pos[n]] << endl;
}
int main()
{
solve();
return 0;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |