题目描述:
Each of Farmer John's N cows (1 ≤ N ≤ 1,000) produces milk at a different positive rate, and FJ would like to order his cows according to these rates from the fastest milk producer to the slowest.
FJ has already compared the milk output rate for M (1 ≤ M ≤ 10,000) pairs of cows. He wants to make a list of C additional pairs of cows such that, if he now compares those C pairs, he will definitely be able to deduce the correct ordering of all N cows. Please help him determine the minimum value of C for which such a list is possible.
输入:
Line 1: Two space-separated integers: N and M
Lines 2..M+1: Two space-separated integers, respectively: X and Y. Both X and Y are in the range 1...N and describe a comparison where cow X was ranked higher than cow Y.
输出:
Line 1: A single integer that is the minimum value of C.
输入样例:
5 5 2 1 1 5 2 3 1 4 3 4
输出样例:
3
解题思路:
把每个奶牛当做结点,奶牛之间的产奶能力的大小关系当做有向边,可以抽象成一个图,而这种关系不仅有之间给出的关系,还有可推导出的关系,如:A->B, B->C 可以得到A->C;而问的需要补充的关系就是图中需要边的总数 - (给出边数量 + 推导边数量)
解题步骤:
1、需要频繁判断两个结点之间是否右边,适合采取邻接矩阵存储边;又因为有结点之间有可推导出的边,用bitset容器创建一个数组存储图;
2、首先结点与本身肯定有关系,在根据输入得到的已知边信息,初始化bitset数组;
3、关系推导:变量bitset数组中的每一个元素,若 i 对 j 有边,则凡是 j 能到达的点 i 都可以到达,用或运算在 i 对应的bitset对象中把所有有关系结点的位置置1.
4、逐个统计在bitset数组中1的个数,之后减去结点数,即可得到已确定的边数,图中需要边的总数 - 已确定的边数即为还需要确定的边数。
代码实现:
#include <iostream>
#include <bitset>
using namespace std;
#define maxn 1001
int n, m;
bitset<maxn> p[maxn];
void Init_and_Insert()
{
int u = 0, v = 0;
for (int i = 1; i <= n; i++)
{
p[i][i] = 1;
}
for (int i = 0; i < n; i++)
{
cin >> u >> v;
p[u][v] = 1;
}
}
void Solve()
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (p[i][j])
{
p[i] |= p[j];
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
ans += p[i].count();
}
cout << n * (n - 1) / 2 - ans + n << endl;
}
int main()
{
cin >> n >> m;
Init_and_Insert();
Solve();
return 0;
}