POJ - 3411 Paid Roads(Dijkstra+状压)

题意:n个城市,m条单向路,每一条路从uv,如果之前已经经过了城市c,花费可以为a也可以为b,没有经过城市c,花费为b,求从城市1n的最小花费

思路:Dijkstra求最短路,多加一维表示已经走过的点的集合。

#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
const int INF = 0x3f3f3f3f;
using namespace std;
struct Edge
{
    int to,Next,c,a,b;
}edge[205];
struct Node
{
    int u,dis,S;
    Node(){}
    Node(int _u,int _dis,int _S) {
        u = _u;
        dis = _dis;
        S = _S;
    }
    bool operator<(const struct Node& oth) const {
        return dis > oth.dis;
    }
};
int dis[11][1 << 11];
bool vis[11][1 << 11];
int tot,head[25],n,m;
void init()
{
    tot = 0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int c,int a,int b)
{
    edge[tot].to = v;
    edge[tot].c = c;
    edge[tot].a = a;
    edge[tot].b = b;
    edge[tot].Next = head[u];
    head[u] = tot++;
}
void dijkstra(int s)
{
    int i,to;
    struct Node t;
    memset(dis,INF,sizeof(dis));
    memset(vis,false,sizeof(vis));
    priority_queue<Node> pq;
    pq.push(Node(s,0,1 << s));
    dis[0][1 << 0] = 0;
    while(!pq.empty()) {
        t = pq.top();
        pq.pop();
        if(vis[t.u][t.S]) continue;
        vis[t.u][t.S] = true;
        for(i = head[t.u]; i != -1; i = edge[i].Next) {
            to = edge[i].to;
            if(t.S & (1 << edge[i].c)) {
                if(dis[to][t.S | (1 << to)] > dis[t.u][t.S] + edge[i].b) {
                    dis[to][t.S | (1 << to)] = dis[t.u][t.S] + min(edge[i].a,edge[i].b);
                    pq.push(Node(to,dis[to][t.S | (1 << to)],t.S | (1 << to)));
                }
                else if(dis[to][t.S | (1 << to)] > dis[t.u][t.S] + edge[i].a) {
                    dis[to][t.S | (1 << to)] = dis[t.u][t.S] + min(edge[i].a,edge[i].b);
                    pq.push(Node(to,dis[to][t.S | (1 << to)],t.S | (1 << to)));
                }
            }
            else {
                if(dis[to][t.S | (1 << to)] > dis[t.u][t.S] + edge[i].b) {
                    dis[to][t.S | (1 << to)] = dis[t.u][t.S] + edge[i].b;
                    pq.push(Node(to,dis[to][t.S | (1 << to)],t.S | (1 << to)));
                }
            }
        }
    }
}
int main(void)
{
    int i,u,v,c,a,b,ans;
    init();
    scanf("%d %d",&n,&m);
    for(i = 0; i < m; i++) {
        scanf("%d %d %d %d %d",&u,&v,&c,&a,&b);
        u--;
        v--;
        c--;
        addedge(u,v,c,a,b);
    }
    dijkstra(0);
    ans = INF;
    for(i = 0; i < (1 << n); i++) {
        ans = min(ans,dis[n - 1][i]);
    }
    if(ans == INF)
        printf("impossible\n");
    else
        printf("%d\n",ans);
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值