旅行(最短路 + 思维 + 暴力枚举)

  1 /**\
  2 https://ac.nowcoder.com/acm/contest/26077/1004
  3 最短路dijstra,既然从a -> b -> c最长,等价求b ->a + b -> c
  4 枚举中继点 然后求出最短路的和的最大值即可
  5 \**/
  6 #include <bits/stdc++.h>
  7 using namespace std;
  8 
  9 const int N = 1e3 + 10;
 10 struct edge
 11 {
 12     int to, w, nextt;
 13 } e[N << 1];
 14 int cnt, head[N];
 15 
 16 bool cmp(int a, int b)
 17 {
 18     return a > b;
 19 }
 20 
 21 void add_edge(int u, int v, int w)
 22 {
 23     e[++cnt].to = v;
 24     e[cnt].w = w;
 25     e[cnt].nextt = head[u];
 26     head[u] = cnt;
 27 }
 28 
 29 struct v
 30 {
 31     int x, dis;
 32     bool operator < (const v& rhs) const
 33     {
 34         return dis > rhs.dis;
 35     }
 36 };
 37 int n, m, dis[N], vis[N];
 38 
 39 int dijstra(int s)
 40 {
 41     memset(vis, 0, sizeof vis);
 42     memset(dis, 0x3f, sizeof dis);
 43 
 44     priority_queue<v> q;
 45 
 46     dis[s] = 0;
 47     q.push({s, 0});
 48 
 49     while(!q.empty())
 50     {
 51         v now = q.top();
 52         q.pop();
 53 
 54         if(vis[now.x]) continue;
 55         vis[now.x] = 1;
 56 
 57         for(int i = head[now.x]; i != -1; i = e[i].nextt)
 58         {
 59             int y = e[i].to;
 60             if(vis[e[i].to]) continue;
 61             if(dis[y] > dis[now.x] + e[i].w)
 62             {
 63                 dis[y] = dis[now.x] + e[i].w;
 64                 q.push({y, dis[y]});
 65             }
 66         }
 67     }
 68 
 69     sort(dis + 1, dis + 1 + n, cmp);
 70 
 71     //dis[n] 就是dis[s] = 0 不用判断
 72     for(int i = 1; i < n - 1; ++i)
 73     {
 74 
 75         if(dis[i] != 0x3f3f3f3f && dis[i + 1] != 0x3f3f3f3f)
 76         {
 77             return dis[i] + dis[i + 1];
 78         }
 79     }
 80     return -1;
 81 }
 82 
 83 void accept()
 84 {
 85     cnt = 0;
 86     memset(head, -1, sizeof head);
 87 
 88     cin >> n >> m;
 89     for(int x, y, z, i = 0; i < m; ++i)
 90     {
 91         cin >> x >> y >> z;
 92         add_edge(x, y, z);
 93         add_edge(y, x, z);
 94     }
 95 
 96     int ans = -1;
 97     for(int i = 1; i <= n; ++i) ans = max(ans, dijstra(i));
 98 
 99     cout << ans << "\n";
100 }
101 
102 signed main()
103 {
104     ios::sync_with_stdio(false);
105     cin.tie(nullptr);
106     cout.tie(nullptr);
107 
108     int _;
109     cin >> _;
110     for(int i = 0; i < _; ++i)
111     {
112         accept();
113     }
114 
115     return 0;
116 }

 

posted @ 2022-03-21 18:02  std&ice  阅读(58)  评论(0编辑  收藏  举报