題面node
關於拓撲排序ios
由於這好幾回考試的題目裏都有在DAG中拓撲排序求最長/短路git
txt說它很是的好用spa
就找了個題作了下code
拓撲排序就是尋找圖中全部的入度爲零的點把他入隊blog
而後再枚舉它全部的連到的點,只要去掉它後又是一個入度爲零的點就繼續入隊排序
在入隊的過程當中不斷更新最小值隊列
直至隊列爲空get
Code:it
#include <queue> #include <cstdio> #include <iostream> using namespace std; const int N = 1e5+7; queue<int> q; int n, m, head[N << 1], dis[N], rd[N]; struct node {int nxt, to;}e[N << 1]; int read() { int s = 0, w = 1; char ch = getchar(); while(!isdigit(ch)) {if(ch == '-') w = -1; ch = getchar();} while(isdigit(ch)) {s = s * 10 + ch - '0'; ch = getchar();} return s * w; } int main() { n = read(), m = read(); for(int i = 1, x, y; i <= m; i++) x = read(), y = read(), e[i].nxt = head[x], e[i].to = y, head[x] = i, rd[y]++; for(int i = 1; i <= n; i++) if(!rd[i]) dis[i] = 1, q.push(i); while(!q.empty()) { int he = q.front(); q.pop(); for(int i = head[he]; i; i = e[i].nxt) { dis[e[i].to] = max(dis[e[i].to], dis[he] + 1); if(!--rd[e[i].to]) q.push(e[i].to); } } for(int i = 1; i <= n; i++) printf("%d\n", dis[i]); return 0; }
謝謝收看, 祝身體健康!