bitset容器应用:洛谷 P2881 排奶牛

题目描述:

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可惜浅灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值