拓扑排序
对于一个有向无环图 G = ( V , E ),其中 V 是顶点集合,E 是边集合。
如果存在一个排列 v1 , v2 , v3 , … , vn (其中 n = | V |)
使得:
对于每一条有向边( u , v ) ∈ E,有 u 排在 v 之前,
即 u 在序列中位于 v 的前面。
const int MAXN = 1005;
struct point
{
vector<int> to;
int val,in, out;
} p[MAXN];
vector<int> ans;
void topological_sort()
{
queue<int> q;
for(int i=0;i<MAXN;i++)
{
if(p[i].in==0)//入度为0的点为起点
q.push(i);
}
while(!q.empty())
{
const int from = q.front();
q.pop();
ans.push_back(from);
for(const int to:p[form].to)
{
p[to].in--;
if(p[to].in==0)
q.push(to);
}
}
if(ans.size()!=MAXN)
{
//存在不能进行拓扑排序的点
//说明图中存在环
}
else
{
//result为拓扑排序结果
}
}