CCF之交通规划

问题描述

试题编号: 201609-4
试题名称: 交通规划
时间限制: 1.0s
内存限制: 256.0MB
问题描述:
问题描述
  G国国王来中国参观后,被中国的高速铁路深深的震撼,决定为自己的国家也建设一个高速铁路系统。
  建设高速铁路投入非常大,为了节约建设成本,G国国王决定不新建铁路,而是将已有的铁路改造成高速铁路。现在,请你为G国国王提供一个方案,将现有的一部分铁路改造成高速铁路,使得任何两个城市间都可以通过高速铁路到达,而且从所有城市乘坐高速铁路到首都的最短路程和原来一样长。请你告诉G国国王在这些条件下最少要改造多长的铁路。
输入格式
  输入的第一行包含两个整数nm,分别表示G国城市的数量和城市间铁路的数量。所有的城市由1到n编号,首都为1号。
  接下来m行,每行三个整数abc,表示城市a和城市b之间有一条长度为c的双向铁路。这条铁路不会经过ab以外的城市。
输出格式
  输出一行,表示在满足条件的情况下最少要改造的铁路长度。
样例输入
4 5
1 2 4
1 3 5
2 3 2
2 4 3
3 4 2
样例输出
11
评测用例规模与约定
  对于20%的评测用例,1 ≤ n ≤ 10,1 ≤ m ≤ 50;
  对于50%的评测用例,1 ≤ n ≤ 100,1 ≤ m ≤ 5000;
  对于80%的评测用例,1 ≤ n ≤ 1000,1 ≤ m ≤ 50000;
  对于100%的评测用例,1 ≤ n ≤ 10000,1 ≤ m ≤ 100000,1 ≤ ab ≤ n,1 ≤ c ≤ 1000。输入保证每个城市都可以通过铁路达到首都。

这道题目可以通过迪杰斯特拉算法来进行求解,考虑到处理的数据量比较大,这里采用优先队列的方式实现最短路的求解。下面给出这道题目的具体代码实现:

<textarea readonly="readonly" name="code" class="c++"> 
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <climits>
using namespace std;

static const int MAX=10000;
static const int WHITE=1;
static const int GRAY=2;
static const int BLACK=3;
int n,m;
int a,b,c;
vector<pair<int,int> >adj[MAX+10];
int mof[MAX+10];
long long ans=0;

void Djs()
{
   priority_queue<pair<int,int> >  PQ;
   int color[MAX];
   int d[MAX];
   for(int i=0;i<n;i++)
    {
      d[i]=INT_MAX;
      color[i]=WHITE;
    }
   d[0]=0;
   mof[0]=0;
   PQ.push(make_pair(0,0));
   color[0]=GRAY;
   while(!PQ.empty())
   {
       pair<int,int> f=PQ.top();
       PQ.pop();
       int u=f.second;

       color[u]=BLACK;

       if(d[u]<f.first*(-1)) continue;
       for(int j=0;j<adj[u].size();j++)
       {
           int v=adj[u][j].first;
           if(color[v]==BLACK) continue;
           if(d[v]>=d[u]+adj[u][j].second)
           {
              d[v]=d[u]+adj[u][j].second;
              if(mof[v]>adj[u][j].second) mof[v]=adj[u][j].second;
              PQ.push(make_pair(d[v]*(-1),v));
              color[v]=GRAY;
           }
       }
   }

   for(int i=0;i<n;i++) ans+=mof[i];
   cout<<ans<<endl;
}

int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++) mof[i]=INT_MAX;
    for(int i=0;i<m;i++)
    {
      cin>>a>>b>>c;
      adj[a-1].push_back(make_pair(b-1,c));
      adj[b-1].push_back(make_pair(a-1,c));
    }
    Djs();
    return 0;
}
</textarea>

猜你喜欢

转载自blog.csdn.net/chengsilin666/article/details/79589958
今日推荐