题目描述

给出一个类似这样

的图,求删掉最多的黑边使得每个特殊点和至少一个节点1连通

保证上下两棵树都存在一种dfs序使得访问特殊点的顺序为1~n

题解

设f[i][j]表示上面的树最后一个特殊点为i,j同理的最小选取数

每次加上lca-->max(i,j)+1的路径,由于题目保证了dfs顺序,所以不会出现不合法的情况

code

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
using namespace std; int a[10001][2];
int ls[5001];
int fa[2][5001][11];
int d[2][5001];
int f[1001][1001];
int n,A,B,i,j,k,l,len,ans; void New(int x,int y)
{
++len;
a[len][0]=y;
a[len][1]=ls[x];
ls[x]=len;
} void dfs(int type,int t)
{
int i; fo(i,1,10)
fa[type][t][i]=fa[type][fa[type][t][i-1]][i-1]; if (t<=n) return; for (i=ls[t]; i; i=a[i][1])
{
fa[type][a[i][0]][0]=t;
d[type][a[i][0]]=d[type][t]+1; dfs(type,a[i][0]);
}
} void swap(int &x,int &y)
{
int z=x;
x=y;
y=z;
} int lca(int type,int x,int y)
{
int i; if (!x)
{
if (!type)
return n+1;
else
return n+A+1;
} if (d[type][x]<d[type][y]) swap(x,y); fd(i,10,0)
if (d[type][fa[type][x][i]]>=d[type][y])
x=fa[type][x][i]; fd(i,10,0)
if (fa[type][x][i]!=fa[type][y][i])
x=fa[type][x][i],y=fa[type][y][i]; if (x!=y)
x=fa[type][x][0]; return x;
} int main()
{
// freopen("f.in","r",stdin); scanf("%d",&n);
scanf("%d",&A);
fo(i,2,A)
{
scanf("%d",&j);
New(j+n,i+n);
}
fo(i,1,n)
{
scanf("%d",&j);
New(j+n,i);
}
scanf("%d",&B);
fo(i,2,B)
{
scanf("%d",&j);
New(j+n+A,i+n+A);
}
fo(i,1,n)
{
scanf("%d",&j);
New(j+n+A,i);
} d[0][n+1]=d[1][n+A+1]=1;
dfs(0,n+1);
dfs(1,n+A+1); memset(f,127,sizeof(f));
f[0][0]=0; fo(i,0,n-1)
{
fo(j,0,n-1)
{
k=max(i,j)+1; l=lca(0,i,k);
f[k][j]=min(f[k][j],f[i][j]+(d[0][k]-d[0][l]-1)); l=lca(1,j,k);
f[i][k]=min(f[i][k],f[i][j]+(d[1][k]-d[1][l]-1));
}
} ans=2133333333;
fo(i,0,n-1)
ans=min(ans,min(f[i][n],f[n][i])); printf("%d\n",(A-1)+(B-1)-ans);
}

最新文章

  1. 使用Logstash进行日志分析
  2. 图的广度优先搜索(BFS)
  3. 【javascript基础】7、继承
  4. CF A. Xenia and Divisors
  5. linux下sqlite3可视化工具
  6. maven项目java包名的路径问题
  7. JDBC之一:JDBC快速入门
  8. mac下安装eclipse以及python
  9. pyqt系列原创入门教程
  10. kafka Centos7.2 单机集群搭建
  11. json、demjson
  12. Adventure 魔幻历险
  13. Presto实战
  14. Java基本数据类型转换
  15. 使用Xutils 3 中遇到的一些问题!!!!
  16. 使用std::find_if提取序列容器的子串
  17. node 问题
  18. 洛谷P4623 [COCI2012-2013#6] BUREK [模拟]
  19. django中的分页设置
  20. Kindle 电子书相关的工具软件【转】

热门文章

  1. LeetCode.989-数组形式的整数做加法(Add to Array-Form of Integer)
  2. LeetCode.914-一副牌中的X(X of a Kind in a Deck of Cards)
  3. linux whoami 显示当前用户的用户名
  4. springboot基于方法级别注解事务的多数据源切换问题
  5. ICPC Asia Nanning 2017 F. The Chosen One (大数、规律、2的k次幂)
  6. 【转】iptables命令、规则、参数详解
  7. 一个php文件就可以把数据库的数据导出Excel表格
  8. Codeforce1196_D_F
  9. java延时队列
  10. 087、日志管理之 Docker logs (2019-05-09)