您的位置:首页 > 其它

poj 1724 roads 图论

2017-10-02 11:24 204 查看
poj 1724

题目大意:N个城市,编号1到N。城市间有R条单向道路。

每条道路连接两个城市,有长度和过路费两个属性。

Bob只有K块钱,他想从城市1走到城市N。求在钱够花的情况下的最短路。如果到不了N,输出-1

思路:dijkstra以长度排序,每次松弛的时候判断钱用完没有,如果没有:松弛;如果用完了则吧进行松弛。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 100 + 2;
int head[maxn],vis[maxn],k = 1,n,r,cost;
struct edge
{
int v,w,next,len;//len表示路的长度,w表示过路费
}e[maxn * maxn];
struct node
{
int now,dis,co;
bool operator < (const node &a) const//以长度排序
{
if(dis != a.dis) return dis > a.dis;
return co > a.co;
}
};
void adds(int u,int v,int len,int w)
{
e[k].v = v;
e[k].w = w;
e[k].len = len;
e[k].next = head[u];
head[u] = k++;
}
priority_queue <node> q;
void dijkstra()
{
node st;
st.dis = 0;
st.co = 0;
st.now =  1;
q.push(st);
while(!q.empty())
{
node no = q.top();
int u = no.now;
q.pop();
if(u == n)
{
printf("%d",no.dis);
return;
}
for(int i = head[u]; i != -1; i = e[i].next)
{
int v = e[i].v;
if(no.co + e[i].w <= cost)//判断钱是否用完
{
node cs;
cs.now = v;
cs.dis = no.dis + e[i].len;
cs.co = no.co + e[i].w;
q.push(cs);
}
}
}
printf("-1");
}
int main()
{
int a,b,c,d;
scanf("%d%d%d",&cost,&n,&r);
memset(head,-1,sizeof(head));
for(int i = 1; i <= r; ++i)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
adds(a,b,c,d);
}
dijkstra();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: