日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

算法提高课-图论-单源最短路的综合应用-AcWing 1135. 新年好:dijkstra和dfs暴搜结合

發布時間:2025/4/5 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法提高课-图论-单源最短路的综合应用-AcWing 1135. 新年好:dijkstra和dfs暴搜结合 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目分析



來源:acwing

分析:

  • 先預處理出從1,a,b,c,d,e出發到其他所有點的單源最短路。存在二維數組dist[6][N]中
  • dfs暴搜所有拜訪順序,共有5!種,對于每一種拜訪順序,可以通過查表的方式算出最短距離。比如拜訪順序是:1,3,2,4,5,6,我們已經預處理好1到3的最短距離,3到2的最短距離,2到4的最短距離等等,總的距離就是加起來。 dfs就是枚舉所有的拜訪順序,求其中最短的距離。
  • ac代碼

    #include<bits/stdc++.h> #define x first #define y second using namespace std; const int N = 50010, M = 2e5 +10; const int INF = 0x3f3f3f3f; typedef pair<int ,int > PII;int n, m; int source[6]; bool st[N];int dist[6][N]; int h[N],e[M],ne[M],w[M],idx;void add(int a, int b, int c){e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++; }void dijkstra(int start, int dist[]){memset(dist, 0x3f, 4*N); // int 4個字節,所以大小是4*Nmemset(st,0, sizeof st);dist[start] = 0;priority_queue<PII,vector<PII>, greater<PII>> heap;heap.push({0,start}); // 距離,點while(heap.size()){auto t = heap.top();heap.pop();int ver = t.y, distance = t.x;if(st[ver]) continue;st[ver] = true;for(int i = h[ver]; ~i; i = ne[i]){int j = e[i];if(dist[j] > distance + w[i]){dist[j] = distance + w[i];heap.push({dist[j], j});}}} }// 枚舉每種拜訪次序,求出最小距離 // 拜訪了u個人,自己是第1個人;當前起點是source[start],當前走過的距離是distance int dfs(int u, int start, int distance){// u== 6表示:拜訪完5個親戚,此時返回最短路if( u == 6) return distance;// res存距離最短的分支int res = INF;for(int i = 1; i<=5; i ++)if(!st[i]){int next = source[i]; // 走親戚ist[i] = true;res = min(res, dfs(u +1, i, dist[start][next] + distance));st[i] = false;}return res; }int main(){cin >> n >> m;memset(h, -1, sizeof h);source[0] = 1; for(int i = 1; i <= 5; i ++) cin >> source[i]; while(m --){int x, y, t;cin >> x >> y >> t;add(x, y, t), add(y, x, t);}// 6 個點,分別求最短路for(int i =0; i < 6; i ++) dijkstra(source[i],dist[i]);/*1. 共有6個人,起點是自己:第1個人2. 當前是source[0]:佳佳3. 當前走過的距離是0*/memset(st,0, sizeof st);printf("%d\n", dfs(1, 0, 0));}

    題目來源

    https://www.acwing.com/problem/content/1137/

    總結

    以上是生活随笔為你收集整理的算法提高课-图论-单源最短路的综合应用-AcWing 1135. 新年好:dijkstra和dfs暴搜结合的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。