Cod sursa(job #983069)

Utilizator stefanzzzStefan Popa stefanzzz Data 10 august 2013 18:33:11
Problema Gather Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.79 kb
#include <fstream>
#include <vector>
#include <queue>
#define MAXN 755
#define MAXK 20
#define INF 2000000000000000000
#define MAXCOD 33000
using namespace std;
ifstream f("gather.in");
ofstream g("gather.out");

struct muchie{
    int nod,lg,maxd;};
struct el_pq{
    int nod,cod;};

int n,m,k,a,camera[MAXK],nrd,p;
long long b,c;
long long dmin[MAXK][MAXK][MAXK],dst[MAXN],dist2[MAXK][MAXCOD];
bool uz[MAXK],uzpq[MAXN],uzhp[MAXK][MAXCOD];
muchie aux;
el_pq x;
vector<muchie> G[MAXN];

struct Comp{
    bool operator()(int a,int b){
        return dst[a]>dst[b];}};
struct Comp2{
    bool operator()(el_pq a,el_pq b){
        return dist2[a.nod][a.cod]>dist2[b.nod][b.cod];}};

priority_queue<int,vector<int>,Comp> pq;
priority_queue<el_pq,vector<el_pq>,Comp2> hp;

void djikstra(int a,int b);

int main(){
    int i,j;
    f>>k>>n>>m;
    for(i=0;i<k;i++)
        f>>camera[i];
    camera[k]=1;
    for(i=1;i<=m;i++){
        f>>a>>b>>aux.lg>>aux.maxd;
        aux.nod=a;
        G[b].push_back(aux);
        aux.nod=b;
        G[a].push_back(aux);}
    for(i=0;i<=k;i++)
        for(j=0;j<k;j++)
            djikstra(i,j);
    for(i=0;i<=k;i++)
        for(j=0;j<(1<<k);j++){
            dist2[i][j]=INF;
            uzhp[i][j]=0;}
    dist2[k][0]=0;
    x.nod=k;
    x.cod=0;
    hp.push(x);
    while(1){
        x=hp.top();
        hp.pop();
        while(uzhp[x.nod][x.cod]){
            x=hp.top();
            hp.pop();}
        if(x.cod==((1<<k)-1))
            break;
        a=x.nod;
        b=dist2[a][x.cod];
        uzhp[a][x.cod]=1;
        nrd=0;
        for(i=0;i<k;i++)
            if(x.cod&(1<<i)){
                uz[i]=1;
                nrd++;}
            else
                uz[i]=0;
        for(i=0;i<k;i++){
            if(uz[i])
                continue;
            x.cod+=(1<<i);
            c=b+dmin[a][nrd][i];
            if(c<dist2[i][x.cod]){
                dist2[i][x.cod]=c;
                x.nod=i;
                hp.push(x);}
            x.cod-=(1<<i);}}
    g<<dist2[x.nod][x.cod]<<'\n';
    f.close();
    g.close();
    return 0;}

void djikstra(int a,int b){
    int i,x=camera[a];
    for(i=1;i<=n;i++){
        dst[i]=INF;
        uzpq[i]=0;}
    dst[x]=0;
    pq.push(x);
    while(!pq.empty()){
        p=pq.top();
        pq.pop();
        while(!pq.empty()&&uzpq[p]){
            p=pq.top();
            pq.pop();}
        if(uzpq[p])
            break;
        uzpq[p]=1;
        for(i=0;i<G[p].size();i++){
            aux=G[p][i];
            if(aux.maxd<b)
                continue;
            if(dst[p]+aux.lg*(b+1)<dst[aux.nod]){
                dst[aux.nod]=dst[p]+aux.lg*(b+1);
                pq.push(aux.nod);}}}
    for(i=0;i<=k;i++)
        dmin[a][b][i]=dst[camera[i]];}