Training 6 - D题
N (1 ≤ N ≤ 100) cows, conveniently numbered 1…N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors.
The contest is conducted in several head-to-head rounds, each between two cows. If cow A has a greater skill level than cow B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B), then cow A will always beat cow B.
Farmer John is trying to rank the cows by skill level. Given a list the results of M (1 ≤ M ≤ 4,500) two-cow rounds, determine the number of cows whose ranks can be precisely determined from the results. It is guaranteed that the results of the rounds will not be contradictory.
Input
- Line 1: Two space-separated integers: N and M
- Lines 2…M+1: Each line contains two space-separated integers that describe the competitors and results (the first integer, A, is the winner) of a single round of competition: A and B
Output
- Line 1: A single integer representing the number of cows whose ranks can be determined
Sample Input
5 5
4 3
4 2
3 2
1 2
2 5
Sample Output
2
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int M = 1e6 + 5;
const int maxn = 1e2 + 5;
int d[maxn][maxn], n, m;
void floyd()
{
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (d[i][k] && d[k][j])
d[i][j] = 1;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
d[x][y] = 1;
}
floyd();
int ans = 0;
for (int i = 1; i <= n; i++)
{
int tmp = 0;
for (int j = 1; j <= n; j++)
if (d[i][j] || d[j][i])
tmp++;
if (tmp == n - 1)
ans++;
}
printf("%d\n", ans);
return 0;
}
思路:
边权值为两头牛是否知道相互等级。套用floyd判断,如果存在一个在i,j之间的点k,且已知i和k、k和j的相互等级关系,且满足全部是大于或全部是小于,那么就认为已知当前i和j的相互等级关系。
对于每一个点,如果已知它和其他n-1个点的相互等级关系,则认为已知它的等级;否则不知道。