60分dfs
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e3+5,INF=0x3f;
int n,m,a[maxn][maxn],vis[maxn],x;
vector<int>g[maxn];
void dfs(int u)
{
for(int i=0;i<g[u].size();i++)
{
int to=g[u][i];
a[x][to]=1;
if(vis[to]==0)
{
vis[to]=1;
dfs(to);
}
}
}
int main()
{
cin>>n>>m;
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
g[u].push_back(v);
}
for(int i=1;i<=n;i++)
{
x=i;
memset(vis,0,sizeof(vis));
dfs(i);
}
int sum=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(a[i][j]==1&&a[j][i]==1&&j!=i)
{
sum++;
//cout<<i<<" "<<j<<endl;
}
cout<<sum/2<<endl;
return 0;
}
Tarjan算法板子
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010, M = 100010;
int n, m;
int h[N], e[M], ne[M], idx;
int dfn[N], low[N];
int stk[N], top, ts;
bool in_stk[N];
int ans;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++ ts;
stk[ ++ top] = u, in_stk[u] = true;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!dfn[j])
{
tarjan(j);
low[u] = min(low[u], low[j]);
}
else if (in_stk[j]) low[u] = min(low[u], dfn[j]);
}
if (dfn[u] == low[u])
{
int y, cnt = 0;
do
{
y = stk[top -- ];
in_stk[y] = false;
cnt ++ ;
} while (y != u);
ans += cnt * (cnt - 1) / 2;
}
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m -- )
{
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
for (int i = 1; i <= n; i ++ )
if (!dfn[i])
tarjan(i);
printf("%d\n", ans);
return 0;
}
作者:yxc
链接:https://www.acwing.com/activity/content/code/content/872415/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。