NC25064 [USACO 2007 Mar G]Ranking the Cows
题目
题目描述
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.
示例1
输入
5 5 2 1 1 5 2 3 1 4 3 4
输出
3
说明
From the information in the 5 test results, Farmer John knows that since cow 2 > cow 1 > cow 5 and cow 2 > cow 3 > cow 4, cow 2 has the highest rank. However, he needs to know whether cow 1 > cow 3 to determine the cow with the second highest rank. Also, he will need one more question to determine the ordering between cow 4 and cow 5. After that, he will need to know if cow 5 > cow 3 if cow 1 has higher rank than cow 3. He will have to ask three questions in order to be sure he has the rankings: "Is cow 1 > cow 3? Is cow 4 > cow 5? Is cow 5 > cow 3?"
题解
知识点:最短路。
题目要求还需要多少对关系才能知道全部关系,根据不等式传递性,我们很容易知道用floyd处理传递闭包,剩下没有被传递到的就是最终需要的答案。
需要注意的是,最终答案是指未知关系的总数,而最终纳入的关系不能被考虑。例如,我不知道 三个关系,则答案是 ,即便如果只要再知道 的关系就能知道其他所有关系,答案也不是 而是 。
最后,这里用了 bitset
优化。
时间复杂度
空间复杂度
代码
#include <bits/stdc++.h> using namespace std; bitset<1007> g[1007]; int main() { std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, m; cin >> n >> m; for (int i = 1;i <= m;i++) { int u, v; cin >> u >> v; g[u][v] = 1; } for (int k = 1;k <= n;k++) { for (int i = 1;i <= n;i++) { if (g[i][k]) g[i] |= g[k];///i通过k中转能到的点 } } int ans = 0; for (int i = 1;i <= n;i++) { for (int j = i + 1;j <= n;j++) { if (!g[i][j] && !g[j][i]) ans++;///注意,这里是朴素比较的此时,不是二分搜索的次数。后者需要上一步结果,而题目答案是在啥都不干的情况下的次数。 } } cout << ans << '\n'; return 0; }
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/17023537.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧