题解 | #牛群的喂养顺序# 拓扑排序
牛群的喂养顺序
https://www.nowcoder.com/practice/ce8860b6a8c74dfd8ccd15998970e447
知识点
拓扑排序
思路
题目给定一些喂养关系,我们可以抽象为假设喂养a之前需要喂养b,我们建立一条从b到a的有向边,因此对整个图跑拓扑排序,如果所有点都可达,就说明能喂养完全。如果有一些点不能喂养(存在环),就不能喂养完全。
时间复杂度
假设点数为n,边数为m;
建图和统计入度时间复杂度为
跑拓扑排序(BFS)每个点只入队一次,时间复杂度为
总体时间复杂度为
AC code(C++)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numCows int整型
* @param feedOrders int整型vector<vector<>>
* @return bool布尔型
*/
bool canFeedAllCows(int numCows, vector<vector<int> >& feedOrders) {
// 拓扑排序
vector<vector<int>> g(numCows);
vector<int> d(numCows, 0);
for (auto& v : feedOrders) {
int a = v[0], b = v[1];
g[b].push_back(a);
d[a] += 1;
}
// bfs
queue<int> q;
for (int i = 0; i < numCows; i ++) {
if (!d[i]) {
q.push(i);
}
}
while (!q.empty()) {
auto t = q.front();
q.pop();
for (auto x : g[t]) {
if (-- d[x] == 0) {
q.push(x);
}
}
}
for (int i = 0; i < numCows; i ++) {
if (d[i]) return false;
}
return true;
}
};
