poj 3635 搜索+优先队列

一定要用优先队列。。。。。TLE了一上午了。。。。。。

AC代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <string>
using namespace std;

#define MAX 0x3f3f3f3f

struct Node{
	int sum_cost;
	int pos;
	int v;
	bool operator<( Node a )const{
		return sum_cost > a.sum_cost;
	}
};

struct Edge{
	int to;
	int length;
	int next;
};

Edge edge[22000];
int head[1010], tot;
int N, M, T;
int V, start, last;
int price[1010];

void add_edge( int a, int b, int length ){
	edge[tot].to = b;
	edge[tot].length = length;
	edge[tot].next = head[a];
	head[a] = tot++;
	edge[tot].to = a;
	edge[tot].length = length;
	edge[tot].next = head[b];
	head[b] = tot++;
}

int BFS(){
	priority_queue<Node> q;
	int dp[1010][110];
	bool mark[1010][110];
	int ans = MAX;
	Node st;
	
	memset( dp, -1, sizeof( dp ) );
	memset( mark, false, sizeof( mark ) );

	st.pos = start;
	st.sum_cost = 0;
	st.v = 0;
	q.push( st );

	while( !q.empty() ){
		Node n = q.top();
		q.pop();

		if( n.pos == last ){
			return n.sum_cost;
		}

		if( mark[n.pos][n.v] ){
			continue;
		}

		mark[n.pos][n.v] = true;

		Node temp = n;//加一升油
		temp.v++;
		temp.sum_cost += price[n.pos];
		if( ( dp[temp.pos][temp.v] == -1 || dp[temp.pos][temp.v] > temp.sum_cost ) && temp.v <= V && !mark[temp.pos][temp.v] ){//不开往下一站
			dp[temp.pos][temp.v] = temp.sum_cost;
			q.push( temp );
		}

		for( int i = head[n.pos]; i != -1; i = edge[i].next ){//开往下一站
			int to = edge[i].to;
			int length = edge[i].length;

			Node temp1 = n;
			temp1.pos = to;
			temp1.v -= length;
			temp1.sum_cost = n.sum_cost;

			if( temp1.v >= 0 ){
				if( ( dp[temp1.pos][temp1.v] == -1 || dp[temp1.pos][temp1.v] > temp1.sum_cost ) && temp1.v <= V && !mark[temp1.pos][temp1.v] ){
					dp[temp1.pos][temp1.v] = temp1.sum_cost;
					q.push( temp1 );
				}
			}
		}
	}

	return ans;
}

int main(){

	while( scanf( "%d%d", &N, &M ) != EOF ){
		
		memset( head, -1, sizeof( head ) );
		tot = 0;

		for( int i = 0; i < N; i++ ){
			cin >> price[i];
		}
		for( int i = 0; i < M; i++ ){
			int temp1, temp2, temp3;
			cin >> temp1 >> temp2 >> temp3;
			add_edge( temp1, temp2, temp3 );
		}

		cin >> T;
		while( T-- ){
			cin >> V >> start >> last;
			 int ans = BFS();
			 if( ans < MAX ){
				cout << ans << endl;
			 }else{
				cout << "impossible" << endl;
			 }
		}

	}
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值