提供一篇目前没被 hack 的题解
考虑 的做法
表示在端点 ,从下往上连了长度 的线。
有 种转移,如图,红色和黑色表示将黑色线接在红色线的中间位置。
设当前节点为 ,儿子为 。
考虑优化
去掉多余的状态。
对于 和 ,当 且 时,显然 无意义,可以删去,最后用 vector 存 即可通过此题。此时已经可以通过官方数据了,但会被菊花图卡。瓶颈在于第二种转移,发现对于儿子节点超过两个的相同状态对此转移无意义,用 map 去重。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=5e4+5;
int n;
vector<pair<int,int> >f[N];
int mn[N];
void work(vector<pair<int,int> >&p){
sort(p.begin(),p.end());
vector<pair<int,int> >tmp;
for(auto i:p){
if(tmp.empty()||i.second+i.first*i.first<tmp.back().second+tmp.back().first*tmp.back().first)tmp.push_back(i);
}
p=tmp;
}
vector<int>e[N];
struct node{
int first,second,id;
};
void dfs(int x,int fa){
for(int y:e[x]){
if(y==fa)continue;
dfs(y,x);
}
int res=0;
for(int y:e[x]){
if(y==fa)continue;
mn[y]=1e18;
for(auto i:f[y]){
int l=i.first,s=i.second;
l++;
mn[y]=min(s+l*l,mn[y]);
}
res+=mn[y];
}
for(int y:e[x]){
if(y==fa)continue;
for(auto i:f[y]){
int l=i.first,s=i.second;
f[x].emplace_back(l+1,res-mn[y]+i.second);
}
}
int ad=1e18;
map<int,map<unsigned long long ,map<long long,int> > >mp;
vector<node >tmp;
for(int y:e[x]){
for(auto i:f[y]){
mp[i.first][i.second][mn[y]]++;
if(mp[i.first][i.second][mn[y]]<=2)tmp.push_back({i.first,i.second,y});
}
}
for(auto i:tmp){
for(auto j:tmp){
if(i.id==j.id)continue;
int tres=res-mn[i.id]-mn[j.id];
ad=min(ad,tres+i.second+j.second+(i.first+j.first+2)*(i.first+j.first+2));
}
}
f[x].emplace_back(0 , ad );
if(e[x].size()==1){
if(e[x][0]==fa){
f[x].emplace_back(0,0);
}
else {
for(auto i:f[e[x][0]]){
f[x].emplace_back(0,i.second+(i.first+1)*(i.first+1));
}
}
}
for(int y:e[x]){
if(y!=fa){
f[y].clear();
f[y].shrink_to_fit();
}
}
work(f[x]);
}
signed main (){
cin>>n;
for(int i=1;i<n;i++){
int x,y;
cin>>x>>y;
e[x].push_back(y);
e[y].push_back(x);
}
dfs(1,0);
if(f[1].empty()){
cout<<"E";
//调试时防止程序崩溃
exit(0);
}
cout<<f[1][0].second;
return 0;
}
