poj3635

bfs+优先队列+邻接链表

细节说明见http://www.xuebuyuan.com/321339.html

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define MAXN 1005
int N, M, cnt;
int oil_price[MAXN];
int dist[MAXN][MAXN];
struct Node{
    int v, w;
    int next;
};
Node node[MAXN * 20];
int head[MAXN];
struct Point{
    int u;
    int rest_oil;
    int cost;
};
int vis[MAXN][105];

bool operator < (const Point& a, const Point& b) {
    return a.cost > b.cost;
}

void add_edge(int u, int v, int c) {
    node[cnt].v = v;
    node[cnt].next = head[u];
    node[cnt].w = c;
    head[u] = cnt ++;
    node[cnt].v = u;
    node[cnt].next = head[v];
    node[cnt].w = c;
    head[v] = cnt ++;
}

void BFS(int capacity, int s, int e) {
    memset(vis, 0, sizeof(vis));
    priority_queue<Point>Q;
    Point start;
    start.u = s;
    start.rest_oil = 0;
    start.cost = 0;
    Q.push(start);
    while(!Q.empty()) {
        Point hd = Q.top();
        Q.pop();
        int u = hd.u;
        vis[u][hd.rest_oil] = 1;
        if(u == e) {
            printf("%d\n", hd.cost);
            return;
        }

        if(hd.rest_oil < capacity && !vis[u][hd.rest_oil + 1]) {
            Point t;
            t.u = u;
            t.rest_oil = hd.rest_oil + 1;
            t.cost = hd.cost + oil_price[u];
            Q.push(t);
        }
        for(int i = head[u]; i != -1; i = node[i].next) {
            if(hd.rest_oil >= node[i].w && !vis[node[i].v][hd.rest_oil - node[i].w]) {
                Point t;
                t.u = node[i].v;
                t.rest_oil = hd.rest_oil - node[i].w;
                t.cost = hd.cost;
                Q.push(t);
            }
        }
    }
    printf("impossible\n");
}

int main() {
    freopen("poj3635.txt", "r", stdin);
    int u, v, c;
    while(scanf("%d%d", &N, &M) != EOF) {
        cnt = 0;
        memset(head, -1, sizeof(head));
        for(int i = 0; i < N; ++ i) {
            scanf("%d", &oil_price[i]);
        }
        while(M --) {
            scanf("%d%d%d", &u, &v, &c);
            add_edge(u, v, c);
        }
        int q, capacity, s, e;
        scanf("%d", &q);
        while(q --) {
            scanf("%d%d%d", &capacity, &s, &e);
            BFS(capacity, s, e);
        }
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值