lightOJ 1174 - Commandos

dijkstra算法,这就是模板题啊。。。


#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

const int MAX_V = 105;
const int INF = 0x3f3f3f3f;
int numV,numE,st,ed;
typedef pair<int,int> P;
struct EDGE
{
  EDGE(int t,int c)
  {
    to = t;
    cost = c;
  }
  int to,cost;
};
vector<EDGE> G[MAX_V];
int d[MAX_V];

void dijkstra(int s)
{
  for (int i = 0; i != numV; i++)
    d[i] = INF;
  priority_queue<P, vector<P>, greater<P> > que;
  for (int i = 0; i != numV; i++)
    d[i] = INF;
  d[s] = 0;
  que.push(P(0,s));
  while (!que.empty())
  {
    P p = que.top();
    int v = p.second;
    que.pop();
    if (d[v] < p.first)
      continue;
    for (int i = 0; i != G[v].size(); i++)
    {
      EDGE e = G[v][i];
      if (d[e.to] > d[v] + e.cost)
      {
        d[e.to] = d[v] + e.cost;
        que.push(P(d[e.to],e.to));
      }
    }
  }
}

int main()
{
  int T, cas = 0;
  cin >> T;
  while (T--)
  {
    cin >> numV >> numE;
    for (int i = 0; i != numV; i++)
    {
      G[i].clear();
    }
    for (int i = 0; i != numE; i++)
    {
      int from,to;
      cin >> from >> to;
      G[from].push_back(EDGE(to,1));
      G[to].push_back(EDGE(from,1));
    }
    cin >> st >> ed;
    dijkstra(st);
    int* d1 = new int[numV];
    for (int i = 0; i != numV; i++)
    {
      d1[i] = d[i];
    }
    dijkstra(ed);
    int max = 0;
    for (int i = 0; i != numV; i++)
    {
      if (max < d[i] + d1[i])
        max = d[i] + d1[i];
      ///cout << d[i] <<" " << d1[i] << endl;
    }
    delete[]d1;
    //cout << max_element(d,d+numV);
    printf("Case %d: ",++cas);
    cout << max << endl;
  }
  return 0;
}


你可能感兴趣的:(图论,dijkstra)