Assume that an engineering project consists of a set of subtasks. Some of the subtasks can be executed in parallel, and some can only be executed after completing some other subtasks. "Task scheduling" includes a set of subtasks and the set of subtasks on which each subtask can be executed.
For example, the completion of all courses and graduation design of a major can be regarded as a project to be completed by an undergraduate, and each course can be regarded as a sub-task. Some courses can be offered at the same time, such as English and C programming, they have no restriction on which one must be taken first; some courses cannot be offered at the same time because they have a sequential dependency, such as two courses of C programming and data structure. The former must be learned first.
But it should be noted that for a group of subtasks, not arbitrary task scheduling is a feasible solution. For example, there is "subtask A depends on subtask B, subtask B depends on subtask C, and subtask C depends on subtask A", then none of these three tasks can be executed first, which is an infeasible Plan. Your job now is to write a program to determine whether any given task scheduling is feasible.
Input format:
Input description: Input the first line to give the number of subtasks N (≤100), and the subtasks are numbered from 1 to N. Next N lines, each line gives a dependency set of a subtask: first, the number of subtasks K in the dependency set is given, and then K subtask numbers are given, and the integers are separated by spaces.
Output format:
If the solution is feasible, output 1; otherwise, output 0.
Question idea: Determine whether there is a ring in a directed graph, and topologically sort.
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int> Graph[105];
int n;
int inDegree[105] = {
0};
int main()
{
cin >> n;
int k,t;
for (int i = 1; i <= n; i++)
{
cin >> k;
while (k--)
{
cin >> t;
Graph[i].push_back(t);
inDegree[t]++;
}
}
queue<int> que;
for (int i = 1; i <= n; i++)
if (!inDegree[i])
que.push(i);
int cnt = 0;
while (!que.empty())
{
int u = que.front();
que.pop();
for (int i = 0; i < Graph[u].size(); i++)
{
int v = Graph[u][i];
inDegree[v]--;
if (!inDegree[v])
que.push(v);
}
cnt++;
}
if (cnt == n)
cout << 1 << endl;
else
cout << 0 << endl;
return 0;
}