利用priority_queue进行广搜,每次弹出距离最短的,并把它能在最大费用内到达的点加入priority_queue
由于memset写得马虎,改了很久。
#include < iostream >
#include < cstdio >
#include < cstdlib >
#include < cstring >
#include < queue >
using namespace std;
#define maxn 105
#define maxr 10005
struct Edge
{
int v, c, l, next;
} edge[maxr];
struct Node
{
int c, l, a;
Node()
{
}
Node( int cc, int ll, int aa): c(cc), l(ll), a(aa)
{
}
};
int n, m, r;
int head[maxn];
int ecount;
void addedge( int a, int b, int l, int c)
{
edge[ecount].next = head[a];
edge[ecount].v = b;
edge[ecount].l = l;
edge[ecount].c = c;
head[a] = ecount;
ecount ++ ;
}
bool operator < ( const Node & a, const Node & b)
{
return a.l > b.l;
}
void work()
{
priority_queue < Node > q;
q.push(Node( 0 , 0 , 1 ));
while ( ! q.empty())
{
Node temp = q.top();
q.pop();
if (temp.a == n)
{
printf( " %d\n " , temp.l);
return ;
}
for ( int i = head[temp.a]; i != - 1 ; i = edge[i].next)
if (temp.c + edge[i].c <= m)
q.push(Node(temp.c + edge[i].c, temp.l + edge[i].l, edge[i].v));
}
printf( " -1\n " );
}
int main()
{
// freopen("t.txt", "r", stdin);
scanf( " %d%d%d " , & m, & n, & r);
ecount = 0 ;
memset(head, - 1 , sizeof (head));
for ( int i = 0 ; i < r; i ++ )
{
int a, b, c, d;
scanf( " %d%d%d%d " , & a, & b, & c, & d);
addedge(a, b, c, d);
}
work();
return 0 ;
}