限制费用的最短路 例题:poj 1724
来源:互联网 发布:洛阳管家婆软件 编辑:程序博客网 时间:2024/05/23 19:16
原题 poj 1724:http://poj.org/problem?id=1724
题意:给你钱数 k,有n个城市(编号1~n),r 条路
然后花费要在k以内,从1到达n城市的最短路。
解法:方法很多:可以用优先队列+bfs(/dijkstra),也可以用spfa+dfs(/dp),也可以用vector 存储一下边的关系。
代码1:优先队列+bfs
#include <iostream>#include <string.h>#include <stdio.h>#include <math.h>#include<queue>#include<algorithm>using namespace std;#define N 120int tot;int first[N]; int k,n,r;struct node{ int u,l,c; friend bool operator <(node a,node b) { if(a.l==b.l) return a.c>b.c; else return a.l>b.l; }};struct edge{ int v,l,c,next;}e[N*N];void addedge(int u,int v,int l,int c,int &tot){ e[tot].v=v; e[tot].l=l; e[tot].c=c; e[tot].next=first[u]; first[u]=tot++;}void init(){ memset(first,-1,sizeof(first)); tot=0;}int bfs(){ priority_queue<node> q; node x; x.u=1,x.c=0,x.l=0; q.push(x); while(!q.empty()) { node now=q.top(); q.pop(); if(now.u==n) return now.l; for(int i=first[now.u];i!=-1;i=e[i].next) { int v=e[i].v,l=e[i].l,c=e[i].c; if(now.c+c>k) continue; node nn; nn.u=v; nn.c=now.c+c; nn.l=now.l+l; q.push(nn); } } return -1;}int main(){ init();scanf("%d%d%d",&k,&n,&r); //cin>>k>>n>>r; int u,v,l,c; for(int i=0;i<r;i++) { scanf("%d%d%d%d",&u,&v,&l,&c); //cin>>u>>v>>l>>c; addedge(u,v,l,c,tot); } printf("%d\n",bfs()); return 0; //cout<<bfs()<<endl;}
代码2:用vector存边
#include <iostream>#include <string.h>#include <stdio.h>#include <math.h>#include<queue>#include<algorithm>#include<vector>using namespace std;#define N 120int k,n,r;struct node{ int v,l,c; friend bool operator <(node a,node b) { if(a.l==b.l) return a.c>b.c; else return a.l>b.l; }};vector<node>e[N];int bfs(){ priority_queue<node> q; node x; x.v=1,x.c=0,x.l=0; q.push(x); while(!q.empty()) { node now=q.top(); q.pop(); if(now.v==n) return now.l; for(int i=0; i<e[now.v].size(); i++) { if(now.c+e[now.v][i].c<=k) { node nn; nn.v=e[now.v][i].v; nn.c=now.c+e[now.v][i].c; nn.l=now.l+e[now.v][i].l; q.push(nn); } } } return -1;}int main(){ scanf("%d%d%d",&k,&n,&r); int u,v,l,c; for(int i=0; i<r; i++) { scanf("%d%d%d%d",&u,&v,&l,&c); e[u].push_back((node){v,l,c}); } printf("%d\n",bfs()); return 0;}
四种算法的模版:http://blog.csdn.net/zhongyanghu27/article/details/8221276
0 0
- 限制费用的最短路 例题:poj 1724
- POJ 1724 最短路费用限制
- 【poj】【费用限制最短路】ROADs
- poj 1724(有限制的最短路)
- poj 1724 spfa(有费用上限的最短路(双重标准最短路))
- poj_1724 ROADS(有费用限制的最短路)
- poj 1724 ROADS 加限制的最短路
- POJ 1724 - ROADS 有限制的最短路,A*
- poj 1724 有限制条件的最短路
- POJ 1724 ROADS (有限制的最短路)
- poj 1062(有限制的最短路)
- 【POJ 1724】Roads (限制最短路)
- POJ 1724ROADS(费用最短路:优先队列+BFS)
- poj 1062 昂贵的聘礼 (有限制的最短路)
- POJ 1062 昂贵的聘礼(限制的最短路)
- POJ 1062 昂贵的聘礼 最短路枚举等级限制
- POJ 3594 带限制的最短路 枚举+SPFA
- POJ 1724 优先队列解带限制最短路
- MongoDB基础操作
- Integer和int大小比较
- 将ipynb文件转换为pdf
- Linux环境Hadoop2.8.0搭建(单机模式-伪分布式模式)
- 大一春季联赛,dfs简单题(思路)
- 限制费用的最短路 例题:poj 1724
- Excel基本操作技巧荟萃 (值得您深入探讨 他懂了) 视频下载20170412-01
- scala与java的区别
- SQL系列(二)集合运算和函数的使用
- SubscriptionManager,SubscriptionInfo,TelephonyManager的使用
- 专利
- Ubuntu下配置ss和chrome插件
- 熵简介
- 读书笔记之设计模式(适配器模式)