poj 1724 有限制条件的最短路

大致题意:给出源点和始点,求花费小于coin的条件下的最短路。

采用优先队列搜索加cost[i]+cost[i->v]<=coin的进队条件(i->vi的邻接点)

#include<iostream>
#include<queue>
#include<cstring>
#include<functional>
using namespace std;
#define MAX_INT 1234567890
struct node
{
	int v;
	int length;
	int value;
	int next;
};
node edge[10001];
int head[101];
struct Node
{
	int v,dist,cost;
	friend bool operator < (const Node a,const Node b)
	{
		if(a.dist==b.dist)
			return a.cost>b.cost;
		return a.dist>b.dist;
	}
};
priority_queue<Node> Q;
int pfs(int n,int coin)
{
	int j,s,k=0;
	Node e={1,0,0};
	Q.push(e);
	while(!Q.empty())
	{
		e=Q.top(),Q.pop();
		if(e.v==n) { k=e.dist; break;}
		for(j=head[e.v];j;j=edge[j].next)
		{
			s=edge[j].v;
			if(e.cost+edge[j].value<=coin)
			{
				Node e1={ s,e.dist+edge[j].length,e.cost+edge[j].value};
				Q.push(e1);
			}
		}
	}
    while(!Q.empty()) Q.pop();
	return k;
}
int main()
{
	int i,k,m,n,coin,N,source,destination,length,value;
	while(cin>>coin>>n>>m)
	{
		memset(head,0,sizeof(head));
		for(N=1,i=0;i<m;i++)
		{
			cin>>source>>destination>>length>>value;
			if(source==destination) continue;
			node e={destination,length,value,N};
			edge[N]=e; 
			edge[N].next=head[source];
			head[source]=N++;
		}
		k=pfs(n,coin);
		if(k==0)
			cout<<"-1"<<endl;
		else
			cout<<k<<endl;
	}
	return 0;
}

 

posted @ 2011-08-16 12:38  书山有路,学海无涯  阅读(396)  评论(0编辑  收藏  举报