给定n个点m条边的稀疏图,对于每一条边,枚举两个端点中度数较少的端点的邻接点,判断是否构成三元环。
#include<stdio.h>
#include<vector>
#include<set>
#include<math.h>
#include<algorithm>
using namespace std;
#define LL long long
vector<int> G[100005];
set<LL> st;
int vis[100005], link[100005], out[100005];
int main(void)
{
LL ans, sum;
int n, i, j, m, k, x, y, z, B;
while(scanf("%d%d", &n, &m)!=EOF)
{
B = sqrt(m);
st.clear();
for(i=1;i<=n;i++)
{
G[i].clear();
vis[i] = out[i] = link[i] = 0;
}
for(i=1;i<=m;i++)
{
scanf("%d%d", &x, &y);
G[x].push_back(y), out[x]++;
G[y].push_back(x), out[y]++;
st.insert((LL)x*n+y);
st.insert((LL)y*n+x);
}
ans = 0;
for(i=1;i<=n;i++)
{
x = i;
vis[x] = 1;
for(j=0;j<G[x].size();j++)
link[G[x][j]] = x;
for(j=0;j<G[x].size();j++)
{
sum = 0;
y = G[x][j];
if(vis[y])
continue;
if(out[y]<=B)
{
for(k=0;k<G[y].size();k++)
{
z = G[y][k];
if(link[z]==x)
sum++;
}
}
else
{
for(k=0;k<G[x].size();k++)
{
z = G[x][k];
if(st.find((LL)z*n+y)!=st.end())
sum++;
}
}
ans += sum*(sum-1)/2;
}
}
printf("%lld\n", ans);
}
}