# My 24ms C++ solution beats 100% using Topology Sort

• ``````bool cmp(const pair<int,int> & a,const pair<int,int> & b)
{
return a.second < b.second;
}

class Solution {
public:
bool canFinish(int num, vector<pair<int, int>>& pre) {
if(!pre.size())
return true;
sort(pre.begin(),pre.end(),cmp);
vector<int> lim(num+1,-1);
vector<int> degree(num,0);
for(auto x:pre)
degree[x.first]++;
for(int i = 1,cnt  = 0; i < pre.size(); i++)
if(pre[i-1].second!=pre[i].second)
lim[pre[i-1].second+1] = i;
lim[pre.back().second+1] = pre.size();
for(int i = 0,llast = 0; i <= num; i++)
if(lim[i] < 0)
lim[i] = llast;
else
llast = lim[i];
queue<int> que;
for(int i = 0; i < num; i++)
if(!degree[i])
que.push(i);
for(int j = 0; j < num; j++)
{
if(que.empty())
return false;
const int t = que.front();que.pop();
for(int i = lim[t]; i < lim[t+1];  i++)
{
degree[pre[i].first]--;
if(!degree[pre[i].first])
que.push(pre[i].first);
}
}
return true;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.