您的位置:首页 > 其它

UVa10537 Toll! Revisited

2017-10-19 19:14 344 查看
题目描述 传送门

考虑到反向做Dijkstra,终点的d值为p,反向Dijkstra时对于当前的(u,v)∈E可以推出如果v是村庄,边权为1;如果是城镇,边权为⌈d(u)/19⌉。为了方便,加了个虚拟终点0。

代码

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cctype>
#define g "%lld"
using namespace std;
typedef long long LL;
const LL INF=1e18;
const int maxn=256,maxm=(maxn-2)*(maxn-1);
bool vis[maxn];
struct Edge{
char t;
int nxt;
Edge(char a=0,int b=0):t(a),nxt(b){}
}edges[maxm*2];
struct heap{
LL d;
int v;
heap(LL a=0,int b=0):d(a),v(b){}
bool operator<(const heap&a)const{
return d>a.d;
}
};
char s[3],t[3];
int h[maxn],n,m,cnt;
LL d[maxn],p;
void dfsput(char u){
if(u==0) return;
int nxt=-1;
LL minv=INF;
vis[u]=1;
for(int i=h[u];i>-1;i=edges[i].nxt) if(u==s[0]||(u!=s[0]&&d[edges[i].t]<d[u])){
if(d[edges[i].t]<minv||(d[edges[i].t]==minv&&edges[i].t<edges[nxt].t)) minv=d[edges[i].t],nxt=i;
}
printf("%c%c",u,edges[nxt].t==0?'\n':'-');
if(nxt>-1) dfsput(edges[nxt].t);
}
void addedge(int from,int to){
edges[++cnt]=Edge(to,h[from]);
h[from]=cnt;
edges[++cnt]=Edge(from,h[to]);
h[to]=cnt;
}
int main(){
int kase=0;
while(scanf("%d",&n)==1&&n!=-1){
printf("Case %d:\n",++kase);
cnt=-1;
memset(h,-1,sizeof(h));
for(int i=0;i<n;i++){
char c1[3],c2[3];
scanf("%s%s",c1,c2);
addedge(c1[0],c2[0]);
}
scanf("%lld%s%s",&p,s,t);
addedge(t[0],0);
memset(vis,0,sizeof(vis));
priority_queue<heap> q;
q.push(heap(p,0));
for(int i=1;i<=255;i++) d[i]=INF;
d[0]=p;
while(!q.empty()){
heap x=q.top();q.pop();
int u=x.v;
if(vis[u]) continue;
vis[u]=1;
for(int i=h[u];i>-1;i=edges[i].nxt){
int v=edges[i].t;
LL k;
if(v==s[0]) k=0;
else if(islower(v)) k=1;
else k=d[u]%19==0?d[u]/19:d[u]/19+1;
if(d[u]+k<d[v]){
d[v]=d[u]+k;
q.push(heap(d[v],v));
}
}
}
printf("%lld\n",d[s[0]]);
memset(vis,0,sizeof(0));
dfsput(s[0]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: