【bfs優先隊列】POJ 3635

來源:互聯網
上載者:User

http://poj.org/problem?id=3635

#define N 1005struct node{    int u;    int len;};vector<node> v[N];int n,m;int price[N];void add(int a,int b,int w){    node tmp;    tmp.u = b;    tmp.len = w;    v[a].push_back(tmp);    tmp.u = a;    v[b].push_back(tmp);}struct Node{    int id;//點編號    int res;//剩餘油量    int val;//最小花費    friend bool operator < (Node a,Node b){        return a.val>b.val;    }};int dp[1001][101];//dp[i][j]表示到達i點後還剩j油量bool vis[1001][101];//選項組是否訪問過int bfs(int c,int s,int t){    priority_queue<Node> pp;    int i,j,k;    dp[s][0] = 0;    Node cur,next;    cur.id = s;    cur.res = 0;    cur.val = 0;    vis[s][0] = 1;    pp.push(cur);    while(!pp.empty()){        cur = pp.top();        pp.pop();        int u = cur.id;        int res = cur.res;        int val = cur.val;        vis[u][res] = 1;        if(u == t){            return val;        }        ///每個點有兩個選擇,要麼自己加油,要麼走到下一點        if(res+1 <= c && !vis[u][res+1] && dp[u][res+1]>dp[u][res] + price[u]){            next.id = u;            next.res = res+1;            next.val = dp[u][res] + price[u];            dp[u][res+1] = dp[u][res]+price[u];            pp.push(next);        }        for(i=0;i<v[u].size();i++){            int vv = v[u][i].u;            k = res-v[u][i].len;            if(k<=c && k>=0 && !vis[vv][k] && val<dp[vv][k]){                dp[vv][k] = val;                next.id = vv;                next.res = k;                next.val = val;                pp.push(next);            }        }    }    return -1;}int main(){    while(scanf("%d%d",&n,&m) != -1){        int i,j,k;        for(i=0;i<n;i++){            v[i].clear();            scanf("%d",&price[i]);        }        while(m--){            int a,b,w;            scanf("%d%d%d",&a,&b,&w);            add(a,b,w);        }        scanf("%d",&m);        while(m--){            int c,s,t;            scanf("%d%d%d",&c,&s,&t);            for(i=0;i<=n;i++){                for(j=0;j<=c;j++){                    dp[i][j] = MAX;                    vis[i][j] = 0;                }            }            int ans = bfs(c,s,t);            if(ans==-1)puts("impossible");            else printf("%d\n",ans);        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.