Uva_140
This topic first stores all vertices in an array when reading data, and stores the relationships between vertices with the adjacent matrix. The reason for sorting vertices in ascending order is mainly because the results are required to output the smallest Lexicographic Order at the same time in the question, and the first compliant solution found in the order after sorting, it must be the smallest solution of the Lexicographic Order.
Then, you only need to enumerate all the arrays and calculate them.
# Include < Stdio. h >
# Include < String . H >
# Include < Ctype. h >
# Include < Stdlib. h >
Int N, [ 10 ], [ 10 ], G [ 30 ] [ 30 ], Vis [ 10 ], ANS [ 10 ], Res;
Char B [ 100 ];
Int CMP ( Const Void * _ P, Const Void * _ Q)
{
Int * P = ( Int * ) _ P;
Int * Q = ( Int * ) _ Q;
Return * P -* Q;
}
Void DFS (cur)
{
Int I, j, temp;
If (Cur = N)
{
Temp = 0 ;
For (I = 0 ; I < N; I ++ )
For (J = I + 1 ; J < N; j ++ )
If (G [A [I] [A [J] && J - I > Temp)
Temp = J - I;
If (Temp < Res)
{
Res = Temp;
Memcpy (ANS,, Sizeof ());
}
Return ;
}
For (I = 0 ; I < N; I ++ )
If ( ! Vis [I])
{
Vis [I] = 1 ;
A [cur] = A [I];
DFS (cur + 1 );
Vis [I] = 0 ;
}
}
Int Main ()
{
Int I, J, K, hash [ 30 ];
While ( 1 )
{
Memset (B, ' \ 0 ' , Sizeof (B ));
Scanf ( " % S " , B );
If (B [ 0 ] = ' # ' )
Break ;
N = 0 ;
Memset (G, 0 , Sizeof (G ));
Memset (hash, 0 , Sizeof (Hash ));
For (I = 0 ; B [I] ! = ' \ 0 ' ;)
{
J = B [I] - ' A ' ;
If ( ! Hash [J])
{
Hash [J] = 1 ;
A [n ++ ] = J;
}
I + = 2 ;
While (Isalpha (B [I])
{
K = B [I] - ' A ' ;
If ( ! Hash [k])
{
Hash [k] = 1 ;
A [n ++ ] = K;
}
G [J] [k] = G [k] [J] = 1 ;
I ++ ;
}
I ++ ;
}
Qsort (A, N, Sizeof ([ 0 ]), CMP );
Memset (VIS, 0 , Sizeof (VIS ));
Res = 1000000000 ;
DFS ( 0 );
For (I = 0 ; I < N; I ++ )
Printf ( " % C " , ANS [I] + ' A ' );
Printf ( " -> " );
Printf ( " % D \ n " , Res );
}
Return 0 ;
}