Cod sursa(job #1592691)

Utilizator turbowin120Amarandei-Stanescu Alexandru turbowin120 Data 7 februarie 2016 20:49:32
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.62 kb
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
const int BUF_SIZE=4096;
const int N=50011, M=200022;
const int INF= 1<<30;

char buf[BUF_SIZE];
int pos=BUF_SIZE;
int d[N],vf[M],cost[M],nr,n,m,lst[N],urm[M],r,a,b,c;
bool viz[N];
int h[2*N],poz[N],k;
int rez[N];
//int lst[100], vf[100], urm[100],a,b,c,n,m,r,nr;
ofstream out("distante.out");
void adauga(int x, int y, int z){

    nr++;
    vf[nr]=y;
    urm[nr]=lst[x];
    cost[nr]=z;
    lst[x]=nr;

}

void schimba(int x, int y){
    int t=h[x];
    h[x]=h[y];
    h[y]=t;

}

void avanseaza(int x){
    int parinte;
    while(x>1){
        parinte=x>>1;

        if(d[h[parinte]]>d[h[x]]){
            poz[h[x]]=parinte;
            poz[h[parinte]]=x;
            schimba(parinte, x);
            parinte=x;


        }

        else x=1;
    }

}

void coboara( int x){
    int fiu;
    while(x<=k){
        fiu=x;
        if((x<<1)<=k){
            fiu=x<<1;
            if(fiu+1<=k){
                if(d[h[fiu+1]]<d[h[fiu]]) fiu++;

            }
        }
        else return;

        if(d[h[x]]>d[h[fiu]]){
            poz[h[x]]=fiu;
            poz[h[fiu]]=x;
            schimba(fiu, x);
            x=fiu;

        }
        else return;
    }

}

void dijkstra(){
    for(int i=1;i<=n;i++){
        d[i]=INF;
        poz[i]=-1;
    }
    k=1;
    d[r]=0;
    poz[r]=1;
    h[1]=r;
    while(k){

        int minim=h[1];
        schimba(1,k);
        poz[h[1]]=1;
        k--;
        coboara(1);

        int p=lst[minim],y;
        while(p){

            y=vf[p];
            if(d[y]>d[minim]+cost[p]){
                d[y]=d[minim]+cost[p];

                if(poz[y]!=-1)
                    avanseaza(y);
                else{
                    h[++k]=y;
                    poz[h[k]]=k;
                    avanseaza(k);

                }
            }
            p=urm[p];
        }
    }


}

void verificare(){
    int v=1;
    for(int i=1;i<=n;i++){
        if(rez[i]!=d[i]) v=0;
    }
    if(v==0) {
        out<<"NU\n";

    }
    else out<<"DA\n";
}

void citire(){
int t;

 FILE *in;
 in=fopen("distante.in","r");
 fscanf(in, "%d", &t);

 for(int i=1;i<=t;i++){
        nr=0;

    fscanf(in, "%d%d%d", &n, &m, &r);
    for(int i=1;i<=n;i++){
        fscanf(in, "%d", &rez[i]);
        lst[i]=0;
    }
    for(int i=1;i<=m;i++){
        fscanf(in, "%d%d%d", &a, &b, &c);
        adauga(a,b,c);
        adauga(b,a,c);

    }
    dijkstra();
    verificare();

 }

}


int main()
{
    citire();
    return 0;
}