【1】题解:P1989 【模板】无向图三元环计数
经典题(无向图三元环计数),但是非常巧妙的均摊分析。
::::info[Trick:无向图定向转 DAG]{open}
考虑给每条边定向。具体的,如果两个端点 deg 不一样,则小 deg 连大 deg,否则小 id 连大 id。这样的图是有向无环的(原始每个环都会出现一个指向方向,从而被拆开)。这样,我们就把一个无向图定向成了 DAG。
::::
拆完之后,原始三元环 \((a,b,c)\) 一定转化成 \(a\to c,b\to c,a\to b\)。然后我们枚举 \(a,b\) 的出边判断即可。这个东西看起来的时间复杂度是非常错误的。但是,你发现这个东西跑起来非常快,那么我们就需要使用均摊分析的方法。
::::info[复杂度均摊分析]{open}
重点在于枚举 \(b\) 之后找 \(b\) 的出边点 \(c\) 是否出现于 \(a\)。我们对这个东西进行均摊分析。
- 如果 \(deg_b\le \sqrt{m}\),则最终的有向图的 \(out_b\le deg_b\le \sqrt{m}\),则这部分点所产生的贡献是 \(\mathcal O(\sqrt{m})\) 的量级的。总量是 \(\mathcal O(m\sqrt{m})\)。
- 否则,我们查看有向图的构造,你会发现一个非常巧妙的事情就是只能有度数 \(\ge\) 其本身的点才能向它连边,由于原图度数和 \(\mathcal O(m)\),则符合条件的点(\(deg\ge \sqrt{m}\))只有 \(\sqrt{m}\) 个,本身只会被计数 \(\mathcal O(\sqrt{m})\) 次,也是 \(\mathcal O(m\sqrt{m})\)。
::::
则这么做的总时间复杂度达到了惊人的 \(\mathcal O(m\sqrt{m})\)。
::::success[丑陋的代码 qwq]
//#define FileIO
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define il inline
bool stMem; double stT=clock();
const int N=1e5+10;
const ll P=998244353;
il ll qp(ll a,ll b=P-2){
ll res=1;
for(;b;b>>=1,a=(a*a)%P) if(b&1) res=(res*a)%P;
return res;
}
// ---------------------------------------------------- //
int n,m, deg[N], mrk[N];
vector<int> e[N], g[N];
vector<pair<int,int>> all_edges;
// ---------------------------------------------------- //
il void solve(){
cin>>n>>m;
for(int i=1;i<=m;++i){
int u,v; cin>>u>>v;
e[u].push_back(v);
e[v].push_back(u);
all_edges.push_back({u,v});
deg[u]++; deg[v]++;
}
for(auto edge:all_edges){
int u=edge.fi, v=edge.se;
if(deg[u]==deg[v]){ if(u>v) swap(u,v); }
else if(deg[u]>deg[v]) swap(u,v);
g[u].push_back(v);
}
int ans=0;
for(int a=1;a<=n;++a){
for(auto b:g[a]) mrk[b]=a;
for(auto b:g[a]) for(auto c:g[b]) if(mrk[c]==a) ++ans;
}
cout<<ans;
return;
}
// ---------------------------------------------------- //
bool edMem;
int main(){
#ifdef FileIO
freopen("file.in","r",stdin);
freopen("file.out","w",stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T=1; //cin>>T;
while(T--) solve();
cerr<<"\n";
cerr<<"[Info] End Of Running. \n";
cerr<<" Time Used : "<<(clock()-stT)/CLOCKS_PER_SEC*1000.00<<" ms\n";
cerr<<" Memory Used : "<<(&stMem-&edMem)/1048576.00<<" Mib\n";
return 0;
}
::::
本题还有 Bitset 加根号分治的无脑做法,由于过于无脑这里不写了(懒)。
文章同步载入于洛谷,详见文章下方链接。
本文来自博客园,作者:Ivan422,转载请注明原文链接:https://www.cnblogs.com/Exfish/p/23325103。

浙公网安备 33010602011771号