Cod sursa(job #2538837)

Utilizator bogdi1bogdan bancuta bogdi1 Data 5 februarie 2020 10:58:14
Problema Gather Scor 40
Compilator cpp-32 Status done
Runda simulare_miri Marime 2.16 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int INF  = 2000000000;
int n;
int celule[20];
int dist1[20][20][20];
int dist[755];
struct Muchie
{
    int y,z,lim;
};
vector<Muchie> g[755];
bool viz[755];
int dp[20][32800];
struct Chesie
{
    int nod,val;
};
struct Comp
{
    bool operator()(const Chesie &a, const Chesie &b)
    {
        return a.val<b.val;
    }
};
priority_queue<Chesie, vector<Chesie>, Comp > pq;
void dijkstra(int nod, int d)
{
    for(int i=1; i<=n; i++)
        dist[i]=INF;
    dist[nod]=0;
    pq.push({nod, 0});
    while(!pq.empty()){
        Chesie u=pq.top();
        pq.pop();
        if(u.val==dist[u.nod]){
            for(int i=0; i<g[u.nod].size(); i++)
                if(g[u.nod][i].lim>=d && dist[g[u.nod][i].y]>dist[u.nod]+g[u.nod][i].z){
                    dist[g[u.nod][i].y]=dist[u.nod]+g[u.nod][i].z;
                    pq.push({g[u.nod][i].y, dist[g[u.nod][i].y]});
                }
        }
    }
}
int main()
{   freopen("gather.in", "r", stdin);
    freopen("gather.out", "w", stdout);
    int k,m,i,x,y,z,d,j,l,minn=INF;
    scanf("%d%d%d", &k, &n, &m);
    for(i=1; i<=k; i++)
        scanf("%d", &celule[i]);
    for(i=1; i<=m; i++){
        scanf("%d%d%d%d", &x, &y, &z, &d);
        g[x].push_back({y, z, d});
        g[y].push_back({x, z, d});
    }
    for(i=1; i<=k; i++)
        for(j=1; j<=k; j++){
            dijkstra(celule[j], i);
            for(l=1; l<=k; l++)
                dist1[j][l][i]=dist[celule[l]];
        }
    for(i=1; i<=k; i++)
        for(j=1; j<(1<<k); j++)
            dp[i][j]=INF;
    dijkstra(1, 0);
    for(i=1; i<=k; i++)
        dp[i][(1<<(i-1))]=dist[celule[i]];
    for(i=1; i<(1<<k); i++){
        int nr=__builtin_popcount(i);
        for(j=1; j<=k; j++)
            if((i&(1<<(j-1)))>0)
                for(l=1; l<=k; l++)
                    if(l!=j && (i&(1<<(l-1)))>0)
                        dp[j][i]=min(dp[j][i], dp[l][i-(1<<(j-1))]+nr*dist1[l][j][nr-1]);
    }
    for(i=1; i<=k; i++)
        minn=min(minn, dp[i][(1<<k)-1]);
    printf("%d", minn);
    return 0;
}