zoj2750-Idiomatic Phrases Game

1918 단어 game
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1750
 
#include<stdio.h>

#include<string.h>

#define MAXN 1000

#define INF 1000000000



struct idiom

{

	char front[ 5 ] ,back [ 5 ] ;

	int T ;

};

idiom dic[ MAXN ];

int Edge[ MAXN ][ MAXN] ;

int dist[ MAXN ] ;

int S[ MAXN ] ;

int N ;





int main()

{

	int  i , j , k ;

	char s[ 100 ] ;

	int len ;

	while( scanf( "%d" ,&N ) != EOF )

	{

		if( N == 0 )

			break;

		for( k = 0 ; k < N ; k++ )

		{

			scanf( "%d%s" , &dic[ k ].T  , s  ) ;

			len = strlen ( s ) ;

			for( i = 0 , j = len - 1; i < 4 ; i++ , j-- )

			{

				dic[ k ].front[ i ] = s[ i ] ;

				dic[ k ].back[ 3 - i ] = s[ j ] ;

			}

			dic[ k ].back[4] = dic[ k ].front[ 4 ] = '\0' ;

		}

		for( i = 0 ; i < N ; i++ )

		{

			for( j = 0 ; j < N ; j++ )

			{

				Edge[ i ][ j ] = INF ;

				if( i == j )

					continue ;

				if( strcmp( dic[ i ].back , dic[ j ].front ) == 0 )

					Edge[ i ][ j ] = dic[ i ].T ;

			}

		}

		

		for( i = 0 ; i < N ; i++ )

		{

			dist[ i ] = Edge[ 0 ][ i ] ;

			S[ i ] =  0 ;

		}

		S[ 0 ] = 1 ;

		dist[ 0 ] =  0 ;

		for( i = 0 ; i < N - 1; i++ )

		{

			int min = INF ;

			int u = 0 ;

			for( j = 0 ; j < N ; j++ )

			{

				if( !S[ j ] && dist[ j ] < min )

				{

					u = j ;

					min = dist[ j ] ;

				}

			}

			S[ u ] = 1 ;

			for( k = 0 ; k < N ; k++ )

			{

				if( !S[ k ] && Edge[ u ][ k ] < INF && Edge[ u ][ k ] + dist[ u ] < dist[ k ] )

					dist[ k ] = dist[ u ] + Edge[ u ][ k ] ;

			}

		}

		if( dist[ N - 1] == INF )

			printf( "-1
" ) ; else printf( "%d
" , dist[ N -1 ] ); } return 0 ; }

 

좋은 웹페이지 즐겨찾기