这个题写的。。有点纠结啊。主要是如果从某地运东西到一个城镇时,根据已知城镇的spoons的数量倒推回去求原来的那个地点spoons的数量有点点麻烦,这里处理好了就应该没有问题了。还有这个字典序的问题。。这里ASCII码越小,字典序越小。
View Code
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 #include <vector> 5 #include <cstdio> 6 #define INF 0x3f3f3f3f3f3f3f3fLL 7 #define maxn 60 8 using namespace std; 9 typedef pair <long long int,int> pii; 10 long long int d[maxn],p; 11 int first[maxn]; 12 vector<int> st,v,next,w,path; 13 int n,m,e,start,end; 14 15 void init() 16 { 17 e = 0; 18 st.clear(); 19 v.clear(); 20 next.clear(); 21 w.clear(); 22 path.clear(); 23 memset(first,-1,sizeof(first)); 24 } 25 void add_edge(int a,int b) 26 { 27 //st[e] = a; 28 st.push_back(a); 29 //v[e] = b; 30 v.push_back(b); 31 //next[e] = first[a]; 32 next.push_back(first[a]); 33 w.push_back(0); 34 first[a] = e; 35 e++; 36 } 37 void Read_Graph() 38 { 39 int i,a,b; 40 char ch1,ch2; 41 e = 0; 42 getchar(); 43 for(i = 1;i <= m;i++) 44 { 45 scanf("%c %c",&ch1,&ch2); 46 getchar(); 47 a = ch1 - 'A'; 48 b = ch2 - 'A'; 49 add_edge(a,b); 50 add_edge(b,a); 51 } 52 scanf("%lld %c %c",&p,&ch1,&ch2); 53 start = ch1 - 'A'; 54 end = ch2 - 'A'; 55 } 56 57 void dijkstra() 58 { 59 priority_queue < pii,vector<pii>,greater<pii> > q; 60 61 int i; 62 for(i = 0;i < maxn;i++) 63 { 64 d[i] = INF; 65 } 66 d[end] = p; 67 q.push(make_pair(p,end)); 68 while(!q.empty()) 69 { 70 while(!q.empty() && q.top().first > d[q.top().second]) q.pop(); 71 int u = q.top().second; 72 q.pop(); 73 if(u == start) break; 74 for(i = first[u];i != -1;i = next[i]) 75 { 76 if(u < 26) 77 { 78 if(d[u] % 19 == 0) 79 { 80 if(d[v[i]] > d[u] / 19 * 20) 81 { 82 d[v[i]] = d[u] / 19 * 20; 83 w[i] = w[i ^ 1] = d[v[i]] - d[u]; 84 q.push(make_pair(d[v[i]],v[i])); 85 } 86 } 87 else if((d[u] + 1) % 19) 88 { 89 if(d[v[i]] > (d[u] + 1) * 20 / 19) 90 { 91 d[v[i]] = (d[u] + 1) * 20 / 19; 92 w[i] = w[i ^ 1] = d[v[i]] - d[u]; 93 q.push(make_pair(d[v[i]],v[i])); 94 } 95 } 96 else 97 { 98 if(d[v[i]] > (d[u] + 1) * 20 / 19 - 1) 99 { 100 d[v[i]] = (d[u] + 1) * 20 / 19 - 1; 101 w[i] = w[i ^ 1] = d[v[i]] - d[u]; 102 q.push(make_pair(d[v[i]],v[i])); 103 } 104 } 105 } 106 else 107 { 108 if(d[v[i]] > d[u] + 1) 109 { 110 d[v[i]] = d[u] + 1; 111 w[i] = w[i ^ 1] = 1; 112 q.push(make_pair(d[v[i]],v[i])); 113 } 114 } 115 } 116 } 117 } 118 119 void solve() 120 { 121 int i,temp,now = start; 122 path.push_back(now); 123 while(now != end) 124 { 125 temp = 1 << 6; 126 for(i = 0;i < e;i++) 127 { 128 if(d[now] == d[v[i]] + w[i] && st[i] == now && w[i] != 0 && v[i] < temp) 129 { 130 temp = v[i]; 131 } 132 } 133 now = temp; 134 path.push_back(now); 135 } 136 printf("%lld\n",d[start]); 137 printf("%c",path[0] + 'A'); 138 for(i = 1;i < path.size();i++) 139 printf("-%c",path[i] + 'A'); 140 printf("\n"); 141 } 142 143 int main() 144 { 145 int ncase = 0; 146 while(scanf("%d",&m)) 147 { 148 if(m == -1) break; 149 init(); 150 Read_Graph(); 151 dijkstra(); 152 printf("Case %d:\n",++ncase); 153 solve(); 154 } 155 return 0; 156 }