Sicily 1031 Campus

大意就是求出两个地点的最短路。

简单的单源最短路问题,我用的是优先队列实现的dijkstra算法,离散数学教的~注意题目的陷阱,输入数据的坑就好啦。


#include <iostream>
#include <map>
#include <vector>
#include <queue>

#define MAXN 205
#define INF 100000000

using namespace std;

int d[MAXN];

class cmp
{
  public:
    bool operator()(const int &a, const int &b) const {return d[a] > d[b];} //优先队列
};

int dijkstra(int a, int b, vector<int> *v, vector<int> *w)
{
  int i, j;
  priority_queue<int, vector<int>, cmp> q;

  for (i = 0; i < MAXN; ++i) d[i] = (i == a) ? 0 : INF;
  q.push(a);

  while (!q.empty())
  {
    j = q.top();
    q.pop();

    for (i = 0; i < v[j].size(); ++i)
    {
      int t = v[j][i];

      if (d[t] > d[j] + w[j][i])
      {
        d[t] = d[j] + w[j][i];//更新最短路
        q.push(t);
      }
    }
  }

  if (d[b] != INF) return d[b];
  return -1;
}

int main()
{
  int t;

  cin >> t;
  while (t --)
  {
    int n, i = 1, j, dis;
    string x, y;
    vector<int> v[MAXN], w[MAXN];//vector实现邻接表储存图
    map<string, int> p;

    cin >> n;
    while (n --)
    {
      cin >> x >> y >> dis;//输入数据的处理
      if (!p.count(x)) p[x] = i++;
      if (!p.count(y)) p[y] = i++;

      v[p[x]].push_back(p[y]);
      w[p[x]].push_back(dis);
      v[p[y]].push_back(p[x]);
      w[p[y]].push_back(dis);
    }

    cin >> x >> y;
    if ( x == y ) cout << 0 << endl; //题目陷阱
    else if ( !p[x] || !p[y] ) cout << -1 << endl;
    else cout << dijkstra(p[x], p[y], v, w) << endl;
  }

  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值