Dijkstra算法,其中要增设一个map容器,使得地点和整数有对应关系。陷阱有三点:一是S和T可能是相等的,此时输出为0;二是S和T可能有一个或两个不出现在map里面,表示无路可走的状态,此时输出为-1;三是默认的最长路程不是100,100只是一条路的最长长度,理论上最长长度出现在a到b需要经过所有的地点(最多100条路,那最多就有200个地点,但若能够一条线串起来的话,最多就是经过100个地点),所以最长路程是100*100=10000。解决了这些问题,剩下的按照Dijkstra算法的一般流程进行就可以了。
Run Time: 0.01sec
Run Memory: 344KB
Code length: 1830Bytes
SubmitTime: 2012-01-06 14:06:16
// Problem#: 1031
// Submission#: 1177042
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
int C, N, D;
string S, T;
int count, sum;
int i, j;
int min, add;
bool included[ 200 ];
int dist[ 200 ];
int road[ 200 ][ 200 ];
cin >> C;
while ( C-- ) {
for ( i = 0; i < 200; i++ ) {
included[ i ] = false;
for ( j = 0; j < 200; j++ )
road[ i ][ j ] = 10001;
road[ i ][ i ] = 0;
}
map<string, int> m;
cin >> N;
count = 0;
while ( N-- ) {
cin >> S >> T >> D;
if ( m.find( S ) == m.end() )
m[ S ] = count++;
if ( m.find( T ) == m.end() )
m[ T ] = count++;
road[ m[ S ] ][ m[ T ] ] = D;
road[ m[ T ] ][ m[ S ] ] = D;
}
cin >> S >> T;
if ( S == T ) {
cout << 0 << endl;
continue;
}
if ( m.find( S ) == m.end() || m.find( T ) == m.end() ) {
cout << -1 << endl;
continue;
}
included[ m[ S ] ] = true;
for ( i = 0; i < count; i++ )
dist[ i ] = road[ m[ S ] ][ i ];
sum = m.size();
while ( --sum ) {
min = 10001;
for ( i = 0; i < count; i++ ) {
if ( !included[ i ] && dist[ i ] < min ) {
add = i;
min = dist[ i ];
}
}
included[ add ] = true;
for ( i = 0; i < count; i++ ) {
if ( !included[ i ] && min + road[ add ][ i ] < dist[ i ] )
dist[ i ] = min + road[ add ][ i ];
}
}
dist[ m[ T ] ] == 10001 ? cout << -1 << endl: cout << dist[ m[ T ] ] << endl;
}
return 0;
}