Skip to main content

P1989 【模版】无向图三元环计数

· 2 min read

参考资料

题意简述

给定一张简单无向图,求其三元环个数。

解题思路

顶点 xx 的度数记为 deg(x)\deg(x),入度记为 in(x)\operatorname{in}(x),出度记为 out(x)\operatorname{out}(x)

将每条无向边按两点的 (deg(x),x)(\deg(x),x) 从小到大定向,得到一张有向无环图(DAG),因为这是 严格全序

在新图中枚举 uu,并按 uwu\to wuvwu\to v\to w 计数,每个三元环只会被顺序最小的顶点统计 11 次。

考虑每个顶点 vv,根据定向规则:

out(v)deg(v)deg(w),wGv\operatorname{out}(v)\le\deg(v)\le\deg(w),\forall w\in G_v out(v)2wGvdeg(w)2m\operatorname{out}(v)^2\le\sum_{w\in G_v}\deg(w)\le 2m out(v)O(m)\operatorname{out}(v)\le O(\sqrt{m})

因此时间复杂度为:

T=O(uvGuout(v))=O(vin(v)out(v))O(vin(v)m)=O(mvin(v))=O(mm)\begin{aligned} T &= O\left(\sum_u\sum_{v\in G_u}\operatorname{out}(v)\right) \\ &= O\left(\sum_v\operatorname{in}(v)\operatorname{out}(v)\right) \\ &\le O\left(\sum_v\operatorname{in}(v)\sqrt{m}\right) \\ &= O\left(\sqrt{m}\sum_v\operatorname{in}(v)\right)=O(m\sqrt{m}) \end{aligned}

参考代码

#include <bits/stdc++.h>
using namespace std;

const int N=200005;
int deg[N],tag[N];
vector<int> G[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,m;
cin>>n>>m;
vector<pair<int,int>> a(m);
for(auto &[u,v]:a)
{
cin>>u>>v;
deg[u]++;
deg[v]++;
}
for(auto [u,v]:a)
{
if(make_pair(deg[u],u)>make_pair(deg[v],v))swap(u,v);
G[u].push_back(v);
}
int ans=0;
for(int u=1;u<=n;u++)
{
for(int w:G[u])tag[w]=u;
for(int v:G[u])for(int w:G[v])if(tag[w]==u)ans++;
}
cout<<ans<<'\n';
return 0;
}