题意:有n个奶牛,给出m个奶牛的关系,即某个奶牛的编程能力比另一个要强,求出能够确定排名的奶牛的最大数量
思路:建立n个点m条边的有向图,某个点能够确定排名,则其他所有点不是可以到达该点,就是可以由该点到达。可以用floyd来判断,给每条边权值赋1,如果松弛后某点与其他所有点的边权值不为无穷大,则该点就能确定排名
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e2+10;
const int inf = 0x3f3f3f3f;
int n, m, g[maxn][maxn];
int main()
{
while (cin >> n >> m) {
memset(g, inf, sizeof(g));
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
g[x][y] = 1;
}
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (g[i][j] > g[i][k] + g[k][j])
g[i][j] = g[i][k] + g[k][j];
int ans = 0;
for (int i = 1; i <= n; i++) {
int cnt = 0;
for (int j = 1; j <= n; j++) {
if (i != j && (g[i][j] != inf || g[j][i] != inf))
cnt++;
}
if (cnt == n-1)
ans++;
}
cout << ans << "\n";
}
return 0;
}
思路2:用两遍dfs,第二遍将边反向,统计一个点能够被到达的次数,若该点在两次dfs后能被其他所有点到达,则该点能确定排名
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e2+10;
const int inf = 0x3f3f3f3f;
int n, m, g[maxn][maxn], d[maxn], vis[maxn];
void dfs(int s)
{
vis[s] = 1;
for (int j = 1; j <= n; j++) {
if (j != s && g[s][j] && !vis[j]) {
dfs(j);
d[j]++;
}
}
}
int main()
{
while (cin >> n >> m) {
memset(g, 0, sizeof(g));
memset(d, 0, sizeof(d));
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
g[x][y] = 1;
}
for (int i = 1; i <= n; i++) {
memset(vis, 0, sizeof(vis));
dfs(i);
}
for (int i = 1; i <= n; i++)
for (int j = 1; j < i; j++) {
swap(g[i][j], g[j][i]);
}
for (int i = 1; i <= n; i++) {
memset(vis, 0, sizeof(vis));
dfs(i);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (d[i] == n-1)
ans++;
}
cout << ans << "\n";
}
return 0;
}