D01 拓扑排序
// Kahn算法 O(n) #include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int N = 100010; int n,m,a,b; vector<int> e[N], tp; int din[N]; bool toposort(){ queue<int> q; for(int i = 1; i <= n; i++) if(din[i]==0) q.push(i); while(q.size()){ int x=q.front(); q.pop(); tp.push_back(x); for(auto y : e[x]){ if(--din[y]==0) q.push(y); } } return tp.size() == n; } int main(){ cin >> n >> m; for(int i=0; i<m; i++){ cin >> a >> b; e[a].push_back(b); din[b]++; } if(!toposort()) puts("-1"); else for(auto x:tp)printf("%d ",x); return 0; }
// DFS算法 O(n) #include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int N = 100010; int n,m,a,b; vector<int> e[N], tp; int c[N]; //染色数组 bool dfs(int x){ c[x] = -1; for(int y : e[x]){ if(c[y]<0)return 0; //有环 else if(!c[y]) if(!dfs(y))return 0; } c[x] = 1; tp.push_back(x); return 1; } bool toposort(){ memset(c, 0, sizeof(c)); for(int x = 1; x <= n; x++) if(!c[x]) if(!dfs(x))return 0; reverse(tp.begin(),tp.end()); return 1; } int main(){ cin >> n >> m; for(int i=0; i<m; i++){ cin >> a >> b; e[a].push_back(b); } if(!toposort()) puts("-1"); else for(int x:tp)printf("%d ",x); return 0; }
分类:
D 图论
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!