Title: http://acm.hdu.edu.cn/showproblem.php?pid=1827
The second strong connected component problem, for SCC also has a certain understanding, so want to summarize here; a strongly connected sub-graph with a non-strongly connected graph is called a strongly connected component (SCC), and all strongly connected components form a DAG in the original image (each strongly connected component is considered a point). The Tarjan () algorithm uses DFS to find strong connected components, we can think of the DFS search process as a whole, the personal sense of step-by simulation is not very good understanding.
Low[]: timestamp; (root).
Dfn[]; Records the time that the current node was searched for.
When a strong connected component is searched, let the root node and its nodes above pop up the stack. (Instack[u] = 0). You can do this by recording the number of SCC && indent && Record the number of nodes in the SCC.
The test instructions is to send the message to everyone by spending the least amount of money in a relational graph.
See SCC in degrees V, v! = 0 Do not need to spend, V = = 0, take the least cost node, pay attention to the consistency of operation.
#include <stack>#include<cstdio>#include<cstring>#include<iostream>using namespacestd;Const intINF =0x3f3f3f3f;intdfn[1001], low[1001], instack[1001], sccf[1001], rdu[1001], cost[1001], CNT_SCC, Vis_num, Total, N, m;structedge{int from, to, next;} edge[ .];intCNT, head[1001];voidADD (intAintb) {Edge E={A, B, head[a]}; EDGE[CNT]=E; Head[a]= cnt++;} Stack<int>S;voidTarjan (intx) { intJ; DFN[X]= Low[x] = + +Vis_num; INSTACK[X]=1; S.push (x); for(inti = head[x]; I! =-1; i =Edge[i].next) { intU =edge[i].to; if(Dfn[u] = =-1) {Tarjan (U); if(Low[x] >Low[u]) low[x]=Low[u]; } Else if(Instack[u] && low[x] >Dfn[u]) low[x]=Dfn[u]; } if(Low[x] = =Dfn[x]) {CNT_SCC++; Do{J=S.top (); SCCF[J]=CNT_SCC; S.pop (); INSTACK[J]=0; } while(J! =x); }}voidDeal ()//determine the result; { for(inti =1; I <= N; i++) { for(intk = Head[i]; K! =-1; K =Edge[k].next) { intU =edge[k].to; if(Sccf[u]! =Sccf[i]) Rdu[sccf[u]]++; } } intReSult =0; for(inti =1; I <= CNT_SCC; i++) { if(!Rdu[i]) {ReSult++; intMinn =INF; for(intj =1; J <= N; J + +) { if(Sccf[j] = =i) Minn=min (Minn, cost[j]); } Total+=Minn; }} printf ("%d%d\n", ReSult, total);}voidSolVe () {Vis_num= CNT_SCC = Total =0; for(inti =1; I <= N; i++) if(Dfn[i] = =-1) Tarjan (i);//printf ("%d\n", CNT_SCC);} voidGetmap () {memset (Rdu,0,sizeof(RDU)); memset (Low,0,sizeof(low)); memset (DFN,-1,sizeof(DFN)); memset (Head,-1,sizeof(head)); memset (Instack,0,sizeof(Instack)); CNT=0; for(inti =1; I <= m; i++) { intA, B; scanf ("%d%d", &a, &b); Add (A, b); }}intMain () { while(~SCANF ("%d%d", &n, &m)) { for(inti =1; I <= N; i++) scanf ("%d", &Cost[i]); Getmap (); SolVe (); Deal (); } return 0;}
Hangzhou Electric 1827--summer Holiday (SCC + indent)