【1】题解:P1989 【模板】无向图三元环计数【均摊分析】【根号分治】【Bitset】

· · 题解

经典题(无向图三元环计数),但是非常巧妙的均摊分析。

::::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。我们对这个东西进行均摊分析。

::::

则这么做的总时间复杂度达到了惊人的 \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 加根号分治的无脑做法,由于过于无脑这里不写了(懒)。