恶补了好几天的算法,英文版看得更懂,呵呵:
/* ID: qq104801 LANG: C++ TASK: comehome */ #include <iostream> #include <fstream> #include <cstring> #include <vector> #include <list> #include <set> #include <queue> #include <cstdio> #include <algorithm> #include <cmath> #define NMAX 52 #define INF 99999 using namespace std; int p; int gg[NMAX][NMAX]; int dd[NMAX]; int vv[NMAX]; int result; int change(char cc) { int index=-1; if(cc>='A' && cc<='Z') index=cc-'A'; else if(cc>='a' && cc<='z') index=cc-'a'+26; else index=-1; return index; } int dijkstra(int s) { int min,k; for(int i=0;i<NMAX;i++) { vv[i]=false; dd[i]=gg[s][i]; } dd[s]=0; vv[s]=1; for(int i=0;i<NMAX;i++) { min=INF; for(int j=0;j<NMAX;j++) if(!vv[j] && dd[j]<min) { min=dd[j]; k=j; } vv[k]=1; for(int j=0;j<NMAX;j++) if(!vv[j] && (min+gg[k][j]<dd[j])) { dd[j]=min+gg[k][j]; } } int mmin=INF; for(int i=0;i<NMAX;i++) { if(dd[i]<mmin && i>=0 && i<=25 && dd[i]>0) { mmin=dd[i]; result=i; } } return mmin; } void test() { freopen("comehome.in","r",stdin); freopen("comehome.out","w",stdout); char ca,cb; int d; for(int i=0;i<NMAX;i++) { gg[i][i]=INF; for(int j=0;j<NMAX;j++) gg[i][j]=INF; } memset(vv,0,sizeof(vv)); cin>>p; while(p--) { cin>>ca>>cb>>d; int ia=change(ca); int ib=change(cb); if(d<gg[ia][ib]) { gg[ia][ib]=d; gg[ib][ia]=d; } } int ans=dijkstra(25); char first='A'+result; cout<<first<<" "<<ans<<endl; } int main () { test(); return 0; }
test data:
USER: cn tom [qq104801] TASK: comehome LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.008 secs, 3384 KB] Test 2: TEST OK [0.005 secs, 3384 KB] Test 3: TEST OK [0.003 secs, 3384 KB] Test 4: TEST OK [0.008 secs, 3384 KB] Test 5: TEST OK [0.008 secs, 3384 KB] Test 6: TEST OK [0.014 secs, 3384 KB] Test 7: TEST OK [0.032 secs, 3384 KB] Test 8: TEST OK [0.008 secs, 3384 KB] Test 9: TEST OK [0.005 secs, 3384 KB] All tests OK. Your program ('comehome') produced all correct answers! This is your submission #3 for this problem. Congratulations! Here are the test data inputs: ------- test 1 ---- 4 d Z 10 b d 2 A b 4 C d 5 ------- test 2 ---- 25 m Z 1000 A m 1000 B m 999 C m 998 D m 997 E m 996 F m 995 G m 994 H m 993 I m 992 J m 991 K m 990 L m 989 M m 988 N m 987 O m 986 P m 985 Q m 984 R m 983 S m 982 T m 981 U m 980 V m 979 W m 978 X m 977 ------- test 3 ---- 28 Z a 1000 a b 1000 b c 1000 c d 1000 d e 1000 e f 1000 f g 1000 g h 1000 h i 1000 i j 1000 j k 1000 k l 1000 l m 1000 m n 1000 n o 1000 o p 1000 p q 1000 q r 1000 r s 1000 s t 1000 t u 1000 u v 1000 v w 1000 w x 1000 x y 1000 y z 1000 z A 1000 A B 1000 ------- test 4 ---- 51 A a 836 B b 836 C c 836 D d 836 E e 836 F f 836 G g 836 H h 836 I i 836 J j 836 K k 836 ................