BFS(60)分
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1010,M = N*N;
typedef pair<int,int> PII;
int n,m;
int h[N],e[M],ne[N],idx;
bool g[N][N];
bool st[N];
queue<PII> q;
void add(int a,int b)
{
e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}
void bfs()
{
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = h[t.second]; i!=-1; i = ne[i])
{
int j = e[i];
if(g[t.first][j]) continue;
q.push({t.first,j});
g[t.first][j] = true;
}
}
}
int main()
{
cin>>n>>m;
memset(h, -1, sizeof h);
for(int i = 0; i<m; i++)
{
int a,b;
cin>>a>>b;
add(a,b);
q.push({a,b});
}
bfs();
int res = 0;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j < i; j ++)
{
if(g[i][j] && g[j][i]) res++;
}
}
cout<<res<<endl;
return 0;
}
DFS(60分)
#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;
}
有向图强连通分量(板子),提高课1174
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 1e4+10, M = 1e5+10;
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);
cout<<ans;
return 0;
}