UVA 11374

以下是本人ac的代码,主要在调格式时花费了很大的功夫。在写输出时确实很笨,还有待改进。放在这里供借鉴和提醒自己优化代码。这个题要注意start和end重合时的情况要单独处理。#include #include #include #include #include #include #include #include #define maxn 505#define maxm 1005#define maxk 1005#define INF 1<<29using namespace std;int n,m,k,s,e;int sdis[maxn],sdone[maxn],spath[maxn],edis[maxn],edone[maxn],epath[maxn];int mindis=0;struct Edge{ int from,to,val; Edge(int from,int to,int val):from(from),to(to),val(val){}};struct HeapNode{ int dis,goal; bool operator < (const HeapNode &mhn) const { return dis>mhn.dis; }};vector edges;vector kedges;vector mmap[maxn],kmap[maxn];void init(int n){ for(int i=1;i<=n;i++) { mmap[i].clear();kmap[i].clear(); } edges.clear(); kedges.clear();}void maddEdge(int x,int y,int z){ edges.push_back(Edge(x,y,z)); int pos=edges.size(); mmap[x].push_back(pos-1); edges.push_back(Edge(y,x,z)); pos=edges.size(); mmap[y].push_back(pos-1);}void kaddEdge(int x,int y,int z){ kedges.push_back(Edge(x,y,z)); int pos=kedges.size(); kmap[x].push_back(pos-1); kedges.push_back(Edge(y,x,z)); pos=kedges.size(); kmap[y].push_back(pos-1);}void dijkstra(int start,int* dis,int* done,int* path){ priority_queue Q; for(int i=1;i<=n;i++) { dis[i]=INF; done[i]=0; path[i]=0; } Q.push(HeapNode{0,start}); dis[start]=0; while(!Q.empty()) { HeapNode mhpn=Q.top();Q.pop(); int goal=mhpn.goal; if(done[goal]) continue; done[goal]=1; int mlen=mmap[goal].size(); for(int i=0;idis[goal]+medge.val) { dis[to]=dis[goal]+medge.val; path[to]=goal; Q.push(HeapNode{dis[to],to}); } } }}void prints(int mend){ if(spath[mend]!=s) { prints(spath[mend]); } printf("%d ",spath[mend]); if(mend==e) { printf("%d\n",mend); }}void printe(int mstart){ if(epath[mstart]!=e) { printf("%d ",epath[mstart]); printe(epath[mstart]); } else printf("%d\n",epath[mstart]);}int main(){ //freopen("in.txt","r",stdin); int x,y,z; bool flag=true; while(~scanf("%d%d%d",&n,&s,&e)) { if(flag) flag=false; else printf("\n"); init(n); scanf("%d",&m); for(int i=0;i<m;i++) { scanf("%d%d%d",&x,&y,&z); maddEdge(x,y,z); } scanf("%d",&k); for(int i=0;i<k;i++) { scanf("%d%d%d",&x,&y,&z); kaddEdge(x,y,z); } if(s==e) { printf("%d\n",s); printf("Ticket Not Used\n"); printf("%d\n",0); continue; } dijkstra(s,sdis,sdone,spath); dijkstra(e,edis,edone,epath); mindis=sdis[e]; int flags=0,flage=0; for(int i=0;isdis[mstart]+edis[mend]+medge.val) { mindis=sdis[mstart]+edis[mend]+medge.val; flags=mstart;flage=mend; } } if(flags==0&&flage==0) { prints(e); //printf("%d\n",e); printf("Ticket Not Used\n"); printf("%d\n",sdis[e]); } else { if(flags!=s) prints(flags); printf("%d ",flags); if(flage==e) printf("%d\n",e); else { printf("%d ",flage); printe(flage); } printf("%d\n",flags); printf("%d\n",mindis); } } return 0;}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值