Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

i want c code first line i input N N is the number of i need to check second line i input [ a ,

i want c code
first line i input N
N is the number of i need to check
second line i input [a,b],[b,c].... etc (then a, b, c ... all of them are the natural numbers.)
if [0,1] mean if i want to check 0 then i need to pass 1
so for example i input line 1=4 and line 2=[[0,1],[1,3],[2,1]]
then
[0,1]= i need to pass 1 to pass 0
[1,3]= i need to pass 3 to pass 1
[2,1]= i need to pass 1 to pass 2
so i pass 3->1->0 or 2-> the other(0 or 2)
this example output = True
but if i input line 1=2, line 2=[[1,0],[0,1]]
then [1,0]= i need to pass 0 to pass 1
[0,1]= i need to pass 1 to pass 0
so i can't pass all of them(because if i want to pass 1 i need pass 0 but i need to pass 1 before pass 0)
in this case output = False
ofcourse [0,0]'s output is Flase(because i can't pass 0)
There are my failure code
#include
#include
#include
using namespace std;
bool canFinish(int numCourses, vector>& prerequisites){
vector> graph(numCourses);
vector inDegree(numCourses,0);
//
for (auto& pre : prerequisites){
graph[pre.second].push_back(pre.first);
inDegree[pre.first]++;
}
queue zeroIndegree;
for (int i =0; i < numCourses; ++i){
if (inDegree[i]==0){
zeroIndegree.push(i);
}
}
int visited =0;
while (!zeroIndegree.empty()){
int course = zeroIndegree.front();
zeroIndegree.pop();
visited++;
for (int next : graph[course]){
if (--inDegree[next]==0){
zeroIndegree.push(next);
}
}
}
// True, False
return visited == numCourses;
}
int main(){
int N; //
cin >> N;
vector> prerequisites;
int a, b;
while (cin >> a >> b){//
prerequisites.push_back({a, b});
}
cout <<(canFinish(N, prerequisites)? "True" : "False")<< endl;
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions