限制费用的最短路 例题: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;}



最短路算法有:dijkstra、spfa、floyd、Bellman_Ford

四种算法的模版:http://blog.csdn.net/zhongyanghu27/article/details/8221276

0 0
原创粉丝点击