POJ 1724 ROADS (有限制的最短路徑DFS/BFS)

來源:互聯網
上載者:User

題意:有n座城市,城市之間有道路,道路需要收費,現在Bob想從城市1去城市n,但是他所擁有的錢是有限制的。現在問Bob能否在有限的錢之內到達n城,若能則輸出最短路徑。
題解:一開始用vector建圖,果斷TLE··。可能是從尾部添加鄰接點的原因吧。

#include <vector>#include <iostream>using namespace std;#define N  10005#define INF 99999struct Edge{int v, len, cost, next;} edge[N];int vis[101], head[N];int ans, k, n, r;void dfs ( int u, int len, int money ){if ( len >= ans )return;if ( u == n ){ans = len;return;}for ( int i = head[u]; i ; i = edge[i].next ){if ( !vis[edge[i].v] &&  money >= edge[i].cost ){vis[edge[i].v] = true;        dfs ( edge[i].v, len + edge[i].len, money-edge[i].cost );    vis[edge[i].v] = false;}}}int main(){int u, v, l, c;memset(vis,0,sizeof(vis));memset(edge,0,sizeof(edge));memset(head,0,sizeof(head));scanf("%d%d%d",&k,&n,&r);int i = 0;while ( r-- ){scanf("%d%d%d%d",&u,&v,&l,&c);i++;edge[i].v = v;edge[i].len = l;edge[i].cost = c;edge[i].next = head[u];head[u] = i;}ans = INF;vis[1] = true;dfs ( 1, 0, k );if ( ans == INF ) printf("-1\n");else printf("%d\n",ans); return 0;}

#include <queue>#include <iostream>using namespace std;#define N  10005struct Edge{int v, len, cost, next;} edge[N];struct Node{int v, len, cost;friend bool operator<(Node a, Node b){        return a.len > b.len;}} node[N];int head[N];int k, n, r;priority_queue<Node> que; /* 優先隊列可以保證每次取出距離最小的點 */int BFS(){Node now, next;now.cost = 0;now.len = 0;now.v = 1;que.push(now);while ( ! que.empty () ){now = que.top ();que.pop();if ( now.v == n )return now.len;for ( int i = head[now.v]; i; i = edge[i].next ){if ( edge[i].cost + now.cost <= k ){next.v = edge[i].v;next.len = edge[i].len + now.len;next.cost = edge[i].cost + now.cost;que.push(next);}}}return -1;}int main(){int u, v, l, c;scanf("%d%d%d",&k,&n,&r);int i = 0;memset(head,0,sizeof(head));while ( r-- ){scanf("%d%d%d%d",&u,&v,&l,&c);i++;edge[i].v = v;edge[i].len = l;edge[i].cost = c;edge[i].next = head[u];head[u] = i;}int ans = BFS();if ( ans == -1 ) printf("-1\n");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.