Cod sursa(job #2166446)

Utilizator DeleDelegeanu Alexandru Dele Data 13 martie 2018 17:09:48
Problema Ubuntzei Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define nmax 2001
#define mmax 10001
#define trece_max 16
#define inf 1<<30
using namespace std;
ifstream f("ubuntzei.in");
ofstream g("ubuntzei.out");
struct heap{int nod,cost;
    bool operator < (const heap &x)const{
         return cost>x.cost;
    }
};
priority_queue<heap>h;
struct nod{int nod,cost;};
vector<nod> a[nmax];
vector<nod>::iterator it;
int n,m,k;
int trece[trece_max];
int perm[trece_max];
int d[nmax][nmax];
void citire(){
   f>>n>>m;
   f>>k;
   for(int i=1 ; i<=k ; ++i)
    f>>trece[i];
    int x,y,z;
   for(int i=1 ; i<=m ; ++i)
   {
       f>>x>>y>>z;
       a[x].push_back({y,z});
       a[y].push_back({x,z});
   }
}
void dijkstra(int x,int d[nmax]){
   for(int i=1 ; i<=n ; ++i)
    d[i]=inf;
   d[x]=0;

   int dist,k,D;
   h.push({x,0});
   while(!h.empty())
   {
       k=h.top().nod;
       D=h.top().cost;
       h.pop();
       if(d[k]==D)
        for(it=a[k].begin() ; it!=a[k].end() ; ++it)
        {
            dist=d[k]+it->cost;
            if(d[it->nod]>dist)
            {
                d[it->nod]=dist;
                h.push({it->nod,dist});
            }
        }
   }
}
int main()
{
    citire();
    if(k==0)
    {
        dijkstra(1,d[1]);
        g<<d[1][n]<<'\n';
        return 0;
    }
    for(int i=1 ; i<=k ; ++i)
        dijkstra(trece[i],d[ trece[i] ]);
    for(int i=1 ; i<=k ; ++i)
        perm[i]=i;
    int mi=inf;
    do{
        int s=d[ trece[perm[1]] ] [1];
        for(int i=2 ; i<=k ; ++i)
            s+=d[ trece[perm[i-1]] ][ trece[perm[i]] ];
        s+=d[ trece[perm[k]] ][n];
        mi=min(mi,s);
    }while(next_permutation(perm+1,perm+k+1));
    g<<mi<<'\n';
    return 0;
}