题解:AT_agc033_f [AGC033F] Adding Edges
Stuart220_Chen · · 题解
图上构造好题。
我们不妨设原图为
我们先考虑
我们现在考虑将原图改成这个形式,对于树上某条简单路径上顺序出现的三个点
现在考虑快速处理这个过程。考虑依次加入
- 当
f(x,y)=y 时,显然不需要加入这条边。 - 当
f(x,y) 有值且不为y 时,我们需要将(f(x,y),y) 加入待加入边的队列。 - 当
f(x,y) 没有值的时候,我们先加入边(x,y) 和边(y,x) (及更新f(x,y) 和f(y,x) 的值),然后更新以x 为根,y 子树内的f(x,u) 为y 。
具体更新方法是如果
最后统计答案时就是分别以每个节点为树的根跑 dfs 统计答案,注意最后答案要除以二,因为我们会正反统计两边。
代码:
#include<bits/stdc++.h>
using namespace std;
#define il inline
struct IO
{
static const int Size=(1<<21);
char buf[Size],*p1,*p2;
int st[105],Top;
~IO(){clear();}
il void clear(){fwrite(buf,1,Top,stdout);Top=0;}
il char gc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,Size,stdin),p1==p2)?EOF:*p1++;}
il void pc(const char c){Top==Size&&(clear(),0);buf[Top++]=c;}
il IO& operator >>(char& c){while(c=gc(),c==' ' || c=='\n' || c=='\r');return *this;}
template<typename T>il IO& operator >>(T& x)
{
x=0;bool f=0;char c=gc();
while(!isdigit(c)){if(c=='-') f=1;c=gc();}
while(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=gc();}
f?x=-x:0;
return *this;
}
il IO& operator >>(string& s)
{
s="";char c=gc();
while(c==' ' || c=='\n' || c=='\r') c=gc();
while(c!=' ' && c!='\n' && c!='\r' && c!=EOF) s+=c,c=gc();
return *this;
}
il IO& operator <<(const char c){pc(c);return *this;}
template<typename T> il IO& operator <<(T x)
{
if(x<0) pc('-'),x=-x;
do st[++st[0]]=x%10,x/=10;while(x);
while(st[0]) pc(st[st[0]--]+'0');
return *this;
}
il IO& operator <<(const string s){for(auto c:s) pc(c);return *this;}
il IO& operator <<(const char* c){for(int i=0;c[i];i++) pc(c[i]);return *this;}
} fin,fout;
const int N=2010;
int f[N][N],p[N][N],ans;
vector<int> g[N];
il void get_fa(int u,int* fa)
{
for(int v:g[u])
{
if(v==fa[u]) continue;
fa[v]=u;
get_fa(v,fa);
}
}
queue<int> qx,qy;
il void dfs(int u,int rt,int t)
{
if(u!=t && p[rt][u])
{
qx.push(u),qy.push(t);
return;
}
p[rt][u]=t;
for(int v:g[u])
{
if(v==f[rt][u]) continue;
dfs(v,rt,t);
}
}
il void add(int u,int v)
{
qx.push(u),qy.push(v);
while(!qx.empty())
{
int x=qx.front(),y=qy.front();
qx.pop(),qy.pop();
if(p[x][y]==y) continue;
if(p[x][y])
{
qx.push(p[x][y]),qy.push(y);
continue;
}
if(p[y][x])
{
qx.push(p[y][x]),qy.push(x);
continue;
}
p[x][y]=y,p[y][x]=x;
dfs(y,x,y);dfs(x,y,x);
}
}
il void get_ans(int u,int rt,int t)
{
if(t!=u && p[t][u])
{
ans++;t=u;
}
for(int v:g[u])
{
if(v==f[rt][u]) continue;
get_ans(v,rt,t);
}
}
signed main()
{
int n,m;fin>>n>>m;
for(int i=1;i<n;i++)
{
int u,v;fin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
for(int i=1;i<=n;i++) get_fa(i,f[i]);
for(int i=1;i<=m;i++)
{
int u,v;fin>>u>>v;add(u,v);
}
for(int i=1;i<=n;i++) get_ans(i,i,i);
fout<<ans/2;
return 0;
}