标签:
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23388 Accepted Submission(s): 5614
import java.util.Scanner; class Trie{ int k =1; private Node root; public Trie() { root = new Node(); } int insert(String str){ Node t = root; int idx; for(int i=0;i<str.length();i++){ if(str.charAt(i)>=‘a‘&&str.charAt(i)<=‘z‘){ idx = str.charAt(i)-‘a‘; }else{ idx = str.charAt(i)-‘A‘+26; } if(t.nodes[idx]==null){ Node node = new Node(); t.nodes[idx] = node; } t = t.nodes[idx]; } if(t.id==0) t.id = k++; return t.id; } class Node{ Node [] nodes; int id; public Node() { nodes = new Node[52]; id = 0; } } } public class Main { static int [][] map; static boolean [] vis; static int [] low; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); if(n==-1) break; map = new int[155][155]; low = new int[155]; vis = new boolean[155]; for(int i=0;i<155;i++){ for(int j=0;j<155;j++){ map[i][j] = 999999999; } } Trie tree = new Trie(); String str1,str2; str1 = sc.next();str2 = sc.next(); int start = tree.insert(str1); int end = tree.insert(str2); for(int i=0;i<n;i++){ str1 = sc.next(); str2 = sc.next(); int a = tree.insert(str1); int b = tree.insert(str2); int c = sc.nextInt(); map[a][b] = map[b][a] = c; } int k = tree.k; int cost = dij(start, end, k); if(cost>=999999999) System.out.println(-1); else System.out.println(cost); } } static int dij(int pos,int end,int n){ for(int i=0;i<n;i++){ low[i] = map[pos][i]; vis[i] = false; } vis[pos] = true; low[pos] = 0; for(int i=1;i<n;i++){ int Min = 999999999; for(int j=0;j<n;j++){ if(Min>low[j]&&!vis[j]){ pos = j; Min = low[j]; } } vis[pos] = true; for(int j=0;j<n;j++){ if(low[j]>low[pos]+map[pos][j]&&!vis[j]){ low[j]=low[pos]+map[pos][j]; } } } return low[end]; } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5487398.html