Poj 3255(dijkstra求次短路)

简介: Poj 3255(dijkstra求次短路)

题目传送门

详情见《挑战程序设计竞赛》P109

代码如下:

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <queue>
#define endl '\n'
using namespace std;
typedef long long ll;
const int N = 5500, INF = 0x3f3f3f3f;
typedef pair<int, int> PII;
struct edge
{
  int to;
  int cost;
};
vector<edge>g[N];
int m, n;
int d1[N];
int dis2[N];
void dijkstra()
{
  priority_queue<PII, vector<PII>, greater<PII> >q;
  fill(d1 + 1, d1 + 1 + n, INF);
  fill(dis2 + 1, dis2 + 1 + n, INF);
  d1[1] = 0;
  q.push({0, 1});
  while (q.size())
  {
    PII t = q.top();
    q.pop();
    int v = t.second, d = t.first;
    if (dis2[v] < d) continue;
    for (int i = 0; i < g[v].size(); i++)
    {
      edge x = g[v][i];
      int d2 = d + x.cost;
      if (d1[x.to] > d2)
      {
        swap(d1[x.to], d2);
        q.push({d1[x.to], x.to});
      }
      if (dis2[x.to] > d2 && d2 > d1[x.to])
      {
        dis2[x.to] = d2;
        q.push({dis2[x.to], x.to});
      }
    }
  }
}
int main()
{
  while (~scanf("%d%d", &n, &m))
  {
    for (int i = 1; i <= m; i++)
    {
      int x, y, z;
      cin >> x >> y >> z;
      g[x].push_back({y, z});
      g[y].push_back({x, z});
    }
    dijkstra();
    cout << dis2[n] << endl;
    return 0;
  }
}


目录
相关文章
|
8月前
|
Java
hdu-1874-畅通工程续(dijkstra + SPFA )
hdu-1874-畅通工程续(dijkstra + SPFA )
46 0
|
人工智能 并行计算 网络架构
|
人工智能
POJ 2370 Democracy in danger(简单贪心)
Democracy in danger Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 3388   Accepted: 2508 Description In one of the...
959 0
poj supermaket (贪心)
http://poj.org/problem?id=1456 #include #include #include using namespace std; struct nod { int a; int d; }; bool cmp(nod x,nod y) { return x.
700 0
|
文件存储
poj 2229 Sumsets 【动态规划】
点击打开题目 Sumsets Time Limit: 2000MS   Memory Limit: 200000K Total Submissions: 13291   Accepted: 5324 Description Far...
928 0