AcWing 3220. 高速公路
原题链接
中等
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
// dfs 60分
const int N = 10000;
int n, m;
int h[N], e[N], ne[N], idx, res;
bool visited[N][N];
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void dfs(int root, int cur)
{
visited[root][cur] = true;
for (int i = h[cur]; ~i; i = ne[i])
{
int neighbor = e[i];
if (visited[root][neighbor])
continue;
dfs(root, neighbor);
}
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
}
for (int i = 1; i <= n; i++)
{
dfs(i, i);
}
res = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j < i; j++)
{
if (visited[i][j] && visited[j][i])
res++;
}
}
cout << res << endl;
return 0;
}