http://www.javashuo.com/article/p-rvrvqjju-br.htmlphp
貌似歷來沒有敲過拓撲排序的板子,,,記錄一下html
拓撲排序就是對DAG有向無環圖中的邊u->v,要求排序出一個點的序列,知足u在v的前面,,ios
算法的思路是不停的將入度爲零的點u放到前面,而且對u能到達的全部點v的入度遞減,,循環處理全部的點便可,,期間將全部入度爲零的點放在一個隊列中,,c++
板子題算法
這道題要求對於多種可能的排序輸出字典序最小的那種,,用優先隊列代替原來的隊列就好了,,數組
priority_queue<int, vector<int>, greater<int> > q;
,頭文件要加 #include <queue>
和 #include <functional>
(一直不知道,,,233,,,代碼:spa
//#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cstdlib> #include <string.h> #include <vector> #include <queue> #include <functional> #define aaa cout<<233<<endl; #define endl '\n' #define pb push_back using namespace std; typedef long long ll; typedef unsigned long long ull; const int inf = 0x3f3f3f3f;//1061109567 const ll linf = 0x3f3f3f3f3f3f3f; const double eps = 1e-6; const double pi = 3.14159265358979; const int maxn = 1e5 + 5; const int maxm = 2e5 + 5; const int mod = 1e9 + 7; inline ll read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } //red_book //l[maxn]爲最後排序的結果 vector<int> g[maxn]; int du[maxn], n, m, l[maxn]; bool toposort() { memset(du, 0, sizeof du); for(int i = 1; i <= n; ++i) for(int j = 0; j < g[i].size(); ++j) ++du[g[i][j]]; int tot = 0; priority_queue<int, vector<int>, greater<int> > q;//按字典序最小的排序時 //queue<int> q; for(int i = 1; i <= n; ++i) if(!du[i]) q.push(i); while(!q.empty()) { int x = q.top(); q.pop(); l[tot++] = x; for(int j = 0; j < g[x].size(); ++j) { int t = g[x][j]; --du[t]; if(!du[t])q.push(t); } } if(tot == n)return 1; else return 0; } int main() { // freopen("233.in" , "r" , stdin); // freopen("233.out" , "w" , stdout); // ios_base::sync_with_stdio(0); // cin.tie(0);cout.tie(0); int u, v; while(scanf("%d%d", &n, &m) != EOF) { for(int i = 0; i <= n; ++i)g[i].clear(); for(int i = 0; i <= n; ++i)du[i] = l[i] = 0; for(int i = 1; i <= m; ++i) { scanf("%d%d", &u, &v); g[u].push_back(v); } toposort(); for(int i = 0; i < n - 1; ++i)printf("%d ", l[i]);printf("%d\n", l[n - 1]); } return 0; }
(end)code