Poj 1094 Problem Solving report
This topic mainly involves the use of topological sorting, which can be seen by any algorithm book. It is not difficult, so it is not difficult.
I use an adjacent table to save the graph, and use DM and DN to save the outbound and inbound degrees of each node (that is, a letter) respectively.
I just want to emphasize the following:
1. first determine whether a loop exists
At the beginning, I directly returned the result when I detected that the sequence could not be determined, but did not determine whether there was a loop. The result was always wa;
2. When the sequence can be determined or the loop is detected, the following input is ignored.
Code:
- # Include <iostream>
- # Include <fstream>
- Using namespace STD;
- Char G [26] [26];
- Int DM [26]; // the sum of each column, that is, the inbound degree of each letter
- Int DN [26]; // The sum of each row, that is, the exit degree of each letter
- Int M, N;
- Char result [27];
- Int toposort ()
- {
- Int index; // start point
- Int r = 0;
- Int count;
- Bool sorted = true;
- Int DMT [26];
- Int DNT [26];
- Memcpy (DMT, DM, sizeof (DMT ));
- Memcpy (DNT, dn, sizeof (DNT ));
- // Find a point with zero degree of access
- For (Int J = 0; j <n; j ++)
- {
- Count = 0;
- For (INT I = 0; I <n; I ++)
- {
- If (0 = DMT [I])
- {
- Index = I;
- Count ++;
- }
- }
- If (0 = count) // discovers the loop
- Return count;
- If (count> 1) Sorted = false;
- For (INT I = 0; I <DNT [Index]; I ++)
- {
- DMT [G [Index] [I]-'a'] --;
- }
- DMT [Index] =-1;
- Result [R ++] = index + 'a ';
- }
- Result [R] = 0;
- If (sorted)
- Return 1; // set the order **
- Else
- Return 2; // The sequence is uncertain.
- }
- Int main ()
- {
- Int I, J, K;
- Char STR [4];
- // Ifstream in ("data. In ");
- Cin> N> m;
- While (N & M)
- {
- K = 0;
- Int found = 0; // The sequence can be completely determined.
- Int incons = 0; // finds a conflict, that is, a loop.
- Memset (DM, 0, sizeof (DM ));
- Memset (DN, 0, sizeof (DN ));
- Memset (G, 0, sizeof (g ));
- For (I = 0; I <m; I ++)
- {
- Cin> STR;
- If (! Found &&! Incons)
- {
- For (j = 0; j <DN [STR [0]-'a']; j ++)
- {
- If (G [STR [0]-'a'] [J] = STR [2])
- Break;
- }
- If (j = DN [STR [0]-'a'])
- {
- G [STR [0]-'a'] [J] = STR [2];
- DM [STR [2]-'a'] ++;
- DN [STR [0]-'a'] ++;
- }
- Int res = toposort ();
- If (1 = res) // The sequence is determined.
- {
- Found = I + 1;
- }
- Else if (0 = res) // finds a conflict
- {
- Incons = I + 1;
- }
- }
- }
- If (found)
- {
- Cout <"sorted sequence determined after" <found <"relations:" <result <"." <Endl;
- }
- Else if (incons)
- {
- Cout <"inconsistency found after" <incons <"relations." <Endl;
- }
- Else
- {
- Cout <"sorted sequence cannot be determined." <Endl;
- }
- Cin> N> m;
- }
- Return 0;
- }