P4173
数学 #dfs
枚举一棵子树断开的边,标记这条边一个子树内的节点,在另一棵树上枚举断开的边,统计子树大小和与第一棵树匹配的点的个数
设第一棵树大小为 \(siz\),第二棵树大小为 \(tot\) ,其中匹配的点数为 \(cnt\)
那么这一对边的 \(S(e_1,e_2)=max(cnt,tot-cnt,siz-cnt,n-tot-siz+cnt)\)
对于每一对边统计答案即可
时间复杂度 \(\mathcal{O}(n^2)\)
// Author: xiaruize
#ifndef ONLINE_JUDGE
bool start_of_memory_use;
#endif
#include <bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
clock_t start_clock = clock();
#endif
#define int long long
#define ull unsigned long long
#define ALL(a) (a).begin(), (a).end()
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define pis pair<int, string>
#define sec second
#define fir first
#define sz(a) int((a).size())
#define Yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define No cout << "No" << endl
#define NO cout << "NO" << endl
#define mms(arr, n) memset(arr, n, sizeof(arr))
#define rep(i, a, n) for (int i = (a); i <= (n); ++i)
#define per(i, n, a) for (int i = (n); i >= (a); --i)
int max(int a, int b)
{
if (a > b)
return a;
return b;
}
int min(int a, int b)
{
if (a < b)
return a;
return b;
}
const int INF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1000000007;
const int N = 4e3 + 10;
int n;
vector<int> g[N], f[N];
int fag[N], faf[N];
bool vis[N];
int cntg = 0;
int cnt[N], siz[N];
void add(int x, int fa)
{
// cerr << "add" << x << endl;
cntg++;
vis[x] = true;
for (auto v : g[x])
if (v != fa)
add(v, x);
}
int res = 0;
void calc(int x, int fa)
{
siz[x] = 1;
cnt[x] = vis[x];
for (auto v : f[x])
{
if (v == fa)
continue;
calc(v, x);
cnt[x] += cnt[v];
siz[x] += siz[v];
}
if (!x)
return;
int tmp = max({cnt[x], cntg - cnt[x], siz[x] - cnt[x], n + 1 - cntg - siz[x] + cnt[x]});
// cerr << x << ' ' << cnt[x] << ' ' << siz[x] << ' ' << cntg << ' ' << tmp << endl;
res += tmp * tmp;
}
void dfs(int x, int fa)
{
// cerr << x << endl;
for (auto v : g[x])
{
if (v != fa)
{
dfs(v, x);
}
}
if (!x)
return;
// cerr << x << ' ' << fa << endl;
cntg = 0;
mms(vis, 0);
add(x, fa);
// cerr << cntg << endl;
mms(cnt, 0);
mms(siz, 0);
calc(0, 0);
// cerr << x << ' ' << res << endl;
}
void solve()
{
cin >> n;
rep(i, 0, n - 1)
{
int x;
cin >> x;
g[i].push_back(x);
g[x].push_back(i);
}
cin >> n;
rep(i, 0, n - 1)
{
int x;
cin >> x;
f[i].push_back(x);
f[x].push_back(i);
}
// cerr << "flag" << endl;
dfs(0, 0);
cout << res << endl;
}
#ifndef ONLINE_JUDGE
bool end_of_memory_use;
#endif
signed main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int testcase = 1;
// cin >> testcase;
while (testcase--)
solve();
#ifndef ONLINE_JUDGE
cerr << "Memory use:" << (&end_of_memory_use - &start_of_memory_use) / 1024.0 / 1024.0 << "MiB" << endl;
cerr << "Time use:" << (double)clock() / CLOCKS_PER_SEC * 1000.0 << "ms" << endl;
#endif
return 0;
}