class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { if (numCourses <= 1) return true;
vector<vector<int>> graph; int in[numCourses]; // 入度 for (int i = 0; i < numCourses; i++) { in[i] = 0; vector<int> t; graph.push_back(t); }
// [0, 1]: 1 -> 0 for (int i = 0; i < prerequisites.size(); i++) { int x = prerequisites[i].first; int y = prerequisites[i].second; in[x]++; graph[y].push_back(x); }
// 暂时不做堆优化,直接暴力 int finished = 0; while (finished < numCourses) { int found = -1; for (int i = 0; i < numCourses; i++) if (in[i] == 0) { found = i; break; } if (found == -1) return false; for (int j = 0; j < graph[found].size(); j++) in[graph[found][j]]--; in[found] = -1; finished++; } return true; } };