Question:
Returns an undirected graph and calculates the number of cut points in the graph. (If vertex I and its adjacent edges are removed, the remaining graph is not connected, Then I is the cut point)
Analysis:
There is a mature DFS Algorithm for Finding cut points. One is written as a backup template.
- /*
- Zju1311 Network
- */
- # Include <stdio. h>
- # Include <memory. h>
- # Define CLR (a) memset (A, 0, sizeof ())
- # Define min (A, B) (a)> (B )? (B) ())
- # Define N 105
- Int N;
- Int a [n] [N];
- Int cut [N];
- Char * Next (char STR [], char * SP ){
- While (* sp & * SP! = '') SP ++;
- While (* sp & * sp = '') SP ++;
- Return sp;
- }
- /**************************************/
- Int ancestor [N];
- Int mark [N];
- Int deep [N];
- Int DFS (int I, int father, int dth, int B [] [N], int cut []) {
- Int j, k, sons = 0, count = 0;
- Mark [I] = 1;
- Deep [I] = ancestor [I] = dth;
- For (k = B [I] [0]; k> = 1; k --){
- J = B [I] [k];
- If (j! = Father & mark [j] = 1) ancestor [I] = MIN (ancestor [I], deep [j]);
- If (mark [j] = 0 ){
- Count + = DFS (j, I, dth + 1, B, cut );
- Sons ++;
- Ancestor [I] = min (ancestor [I], ancestor [J]);
- If (Father =-1 & Sons> 1) | (father! =-1 & ancestor [J]> = deep [I])
- Cut [I] = 1;
- // If (ancestor [J]> deep [I]) brige [I] [J] = 1;
- }
- }
- Mark [I] = 2;
- Return count + cut [I];
- }
- /*
- Cut Point
- Parameter: A [] [] adjacent matrix. Non-0 represents connectivity. N.
- Return: Number of cut points. Cut [I] = 1 indicates that I is a cut point.
- Note: The DFS algorithm first converts the adjacent matrix into an adjacent table to handle the situation where the graph itself is not connected. Complexity O (E)
- The bridge where the image can be modified.
- */
- Int cutpoints (int A [] [N], int N, int cut []) {
- Int I, j, B [N] [N], Count = 0;
- For (I = 0; I <n; I ++) Cut [I] = B [I] [0] = 0;
- Memset (mark, 0, sizeof (Mark ));
- For (I = 0; I <n; I ++) for (j = 0; j <n; j ++) if (a [I] [J]) B [I] [++ B [I] [0] = J;
- For (I = 0; I <n; I ++) if (MARK [I] = 0) Count + = DFS (0,-1, 0, B, cut );
- Return count;
- }
- /**************************************/
- Int main ()
- {
- Int I, J, K;
- Char STR [N * 10], * sp;
- While (scanf ("% d", & N )! = EOF & N ){
- // Init
- CLR ();
- // Input
- While (scanf ("% d", & I), I ){
- Gets (STR );
- For (sp = next (STR, STR); sscanf (SP, "% d", & J )! = EOF; SP = next (STR, SP )){
- A [I-1] [J-1] = A [J-1] [I-1] = 1;
- }
- }
- // Work
- Printf ("% d/N", cutpoints (A, N, cut ));
- }
- Return 0;
- }