手打代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 #include <bits/stdc++.h> using namespace std;const int N=100005 ;int scc[N],siz[N],cnt;int stk[N],instk[N],top;int dfn[N],low[N],tot;int n,m,ans;vector<int >G[N]; void tarjin (int x) { dfn[x]=low[x]=++tot; stk[++top]=x; instk[x]=1 ; for (auto y : G[x]){ if (!dfn[y]){ tarjin (y); low[x]=min (low[x],low[y]); } else if (instk[y]){ low[x]=min (low[x],dfn[y]); } } if (dfn[x]==low[x]){ ++cnt; int y; do { y=stk[top--]; instk[y]=0 ; scc[y]=cnt; ++siz[cnt]; }while (y!=x); } } int main () { int u,v; cin>>n>>m; for (int i=1 ;i<=m;i++){ cin>>u>>v; G[u].push_back (v); } for (int i=1 ;i<=n;i++)if (!dfn[i])tarjin (i); for (int i=1 ;i<=cnt;i++){ if (siz[i]>1 )ans++; } cout<<ans; return 0 ; }
AI分析 缩点模板题的核心流程。代码用 Tarjan 求出所有强连通分量,并把每个节点映射到对应的分量编号,同时统计每个分量包含的点数。这里只统计点数大于 1 的分量个数,可以看作是缩点流程的骨架版本,还没有加上分量权值合并和 DAG 上求最长路的部分。理解这段代码的关键是明白 dfn 与 low 的含义,以及为什么在 dfn 等于 low 时栈中从栈顶到该节点的元素恰好构成一个强连通分量。掌握之后,补上拓扑排序与 DP 就能解决大部分缩点类题目。
另外,缩点之后需要把分量内部的权值合并,再在 DAG 上按拓扑序转移,才能求出最大权路径。这份代码可以当作第一步,后续补充部分并不复杂。