您的位置:首页 > 其它

POJ 3635 bfs+优先队列(最短路本质,好题)

2012-06-26 10:34 274 查看
题目链接: http://poj.org/problem?id=3635

题目大意及分析:

  http://hi.baidu.com/legend_ni/blog/item/c7525409cf8057f036d1229d.html

  http://ip96cns.blog.163.com/blog/static/1700951922011215104442567/

  显然这题我不会,后来觉得应该要dp的才是,因为前后总是会有影响。

  看了解题报告后似乎有点明白,然后自己实现了代码,发现比上面链接里的代码略了一个数组dp[][],我的代码还是比他们的更有可取之处的,我想我以前还是不曾深入地认识bfs+优先队列。

  另外能把100个容量分成1个个来作为状态进行bfs也是需要勇气和经验的。

注意代码里面 vis[][]=1 的赋值必须是在出队列的时候才可以,否则按我之前的一个写法(见下面第二个代码)是错误的。

AC代码:

View Code

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

#define mpair make_pair
#define pii pair<int,int>
#define MM(a,b) memset(a,b,sizeof(a));
typedef long long lld;
typedef unsigned long long u64;
template<class T> bool up_max(T& a,const T& b){return b>a? a=b,1 : 0;}
template<class T> bool up_min(T& a,const T& b){return b<a? a=b,1 : 0;}
#define maxn 1010

int n,m;
int p[maxn];
vector< pii > map[maxn];

struct Node{
int u, vol, cost; /// u: cur node;
Node(int u_,int vol_,int cost_){u=u_,vol=vol_,cost=cost_;}
bool operator<(Node a)const{
return cost > a.cost; ///
}
};
priority_queue<Node> Q;

bool vis[maxn][105];
int bfs(int VOL, int st, int ed){
MM( vis, 0 );
while( !Q.empty() ) Q.pop();
Q.push( Node( st, 0, 0 ) );
vis[st][0]= 1;
while( !Q.empty() ){
Node a= Q.top(); Q.pop();
int u= a.u, vol= a.vol, cost= a.cost;
if( u==ed ) return cost;

/// we choose to add a unit fuel;
if( vol<VOL && !vis[u][vol+1] ){
Q.push( Node( u, vol+1, cost+p[u] ) );
vis[u][vol+1]= 1;
}

/// we choose to go to the next node;
for(int i=0;i<map[u].size();++i){
int v= map[u][i].first, w= map[u][i].second;
if( vol>=w && !vis[v][vol-w] ){
Q.push( Node( v, vol-w, cost ) );
vis[v][vol-w]= 1;
}
}
}
return -1;
}

int main()
{
//freopen("poj3635.in","r",stdin);
while( cin>>n>>m ){
int i,u,v,x,q;
for(i=0;i<n;++i) scanf("%d", p+i), map[i].clear();
while( m-- ){
scanf("%d%d%d", &u,&v,&x);
map[u].push_back( pii( v, x ) );
map[v].push_back( pii( u, x ) );
}

cin>>q;
while( q-- ){
scanf("%d%d%d", &x, &u, &v);
int ans= bfs(x, u, v);
if( -1==ans ) puts("impossible");
else printf("%d\n", ans);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: