[Acwing#848.]有向图的拓扑序列

题目来源:https://www.acwing.com/problem/content/description/850/

给定一个n个点m条边的有向图,图中可能存在重边和自环。

请输出任意一个该有向图的拓扑序列,如果拓扑序列不存在,则输出-1。

若一个由图中所有点构成的序列A满足:对于图中的每条边(x, y),x在A中都出现在y之前,则称A是该图的一个拓扑序列。

输入格式
第一行包含两个整数n和m

接下来m行,每行包含两个整数x和y,表示点x和点y之间存在一条有向边(x, y)。

输出格式
共一行,如果存在拓扑序列,则输出拓扑序列。

否则输出-1。

数据范围
1≤n,m≤105
输入样例:
3 3
1 2
2 3
1 3
输出样例:
1 2 3


拓扑排序模板题,只需新建一个数组topu[]用来保存拓扑序列,需要注意的是自环也是环,有自环就不是DAG了。 ``` #include using namespace std; const int maxn = 1e5+1; vector G[maxn]; int n, m, indg[maxn], topu[maxn];

void rd(){
scanf("%d %d", &n, &m);
memset(indg, 0, sizeof(indg));
for(int i=1; i<=m; i++){
int x, y;
scanf("%d %d", &x, &y); // 自环也是环,就不是DAG
G[x].push_back(y);
indg[y]++;
}
}

bool topusort(){
int cnt = 0;
queue q;
for(int i=1; i<=n; i++){
if(indg[i]0){
q.push(i);
topu[++cnt] = i;
}
}
while(!q.empty()){
int u = q.front();
q.pop();
for(int i=0; i<G[u].size(); i++){
int v = G[u][i];
indg[v]--;
if(indg[v]
0){
q.push(v);
topu[++cnt] = v;
}
}
}
if(cnt==n)
return true;
return false;
}

int main(){
rd();
if(topusort())
for(int i=1; i<=n; i++) printf("%d ", topu[i]);
else
printf("-1");
return 0;
}

posted @ 2019-09-24 15:03  gdgzliu  阅读(509)  评论(0编辑  收藏  举报