O (V+e)
The usual Tarjan notation is a dfn[] array followed by a instack[] array, and I've streamlined the code to delete both of these arrays, replacing them with simpler notation, and saving space.
int LOW[MAXN]; Record the earliest ancestors the tree can reach (not necessarily the earliest, but not the use) int time; timestamp int num; Number of connected components int BELONG[MAXN]; The record belongs to which connected component int STA[MAXN]; handwritten stack int top;
Stack top void init () {num = time = top = 0;
memset (low,-1,sizeof (Low));
Memset (Belong,-1,sizeof (belong)); } void Tarjan (int p) {int t=time;
Record the time stamp when accessing this point, do not DFN array low[p]=time++;
Sta[top++]=p;
for (int i=v[p].size () -1;i>=0;i--) {int next=v[p][i];
if (low[next]==-1) {//has not been visited Tarjan (next);
Low[p]=min (Low[p],low[next]); } else if (belong[next]==-1)//is still in the stack (as long as the stack is out, the value of belong is definitely determined, this way of judging the instack array is saved) Low[p]=min (Low[p],low
[Next]);
} if (low[p]==t) {while (1) {int i=sta[--top]; Belong[i]=num;
The connected component number starts with 0 if (i==p) break;
} num++;
}} void Solve () {init ();
for (int i=1;i<=n;i++) if (low[i]==-1) Tarjan (i); }