Cod sursa(job #1351666)

Utilizator MKLOLDragos Ristache MKLOL Data 21 februarie 2015 11:22:59
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include<stdio.h>
#include<vector>
using namespace std;
#define pb push_back
#define INF 1010010101011
#define Nmax 100500
int coad[Nmax*20],viz[Nmax],nrviz[Nmax],x,y,z,N,M,S=1,k,st,ok=1;
long long best[Nmax];
vector<int> mcl;
int smc[2*Nmax];
struct Nod{
    int cost,val,nrmuchie;
    Nod *next;} *l[Nmax];
void adauga(int x,int y,int z,int nr)
{
    Nod *q=new Nod;
    q->val=y;
    q->nrmuchie=nr;
    q->cost=z;
    q->next=l[x];
    l[x]=q;
}
void make_bell(int p)
{
    viz[p]=0;
    for(Nod *it=l[p];it!=NULL;it=it->next)
    {

     if(best[it->val]>best[p]+(it->cost))
        {
            best[it->val]=best[p]+it->cost;
            if(viz[it->val]==0)
            {
                viz[it->val]=1;
                coad[k++]=it->val;
                ++nrviz[it->val];
            if(nrviz[it->val]==N+1)
                ok=0;
            }
        }
    }
}
void dfs(int x){
    viz[x]=1;
    //printf("%d ",x);
    for(Nod *it=l[x];it!=NULL;it=it->next){
        int nod = it->val;
        int nr = it->nrmuchie;
        if(best[x] + (it->cost) == best[nod]){
            if(viz[nod] == 0)
            {
                mcl.pb(nr);
                smc[nr]=1;
                dfs(nod);
            }
        }
    }
}
int main()
{
    freopen("algoritm.in","r",stdin);
    freopen("algoritm.out","w",stdout);
    int T;
    scanf("%d",&T);
    while(T--) {
        scanf("%d%d",&N,&M);
        //printf("%d %d\n",N,M);
        k=0;
        S=1;
        ok=1;
        st=0;
        mcl.clear();
        for(int i=1;i<=N;++i){
            nrviz[i]=0;
            best[i]=INF;
            l[i] = NULL;
            viz[i] = 0;
        }
        for(int i=1;i<=M;++i)
            {
                smc[i]=0;
                scanf("%d%d%d\n",&x,&y,&z);
                adauga(x,y,z,i);
            }

        coad[k++]=S;
        viz[S]=1;
        best[S]=0;
        nrviz[S]=1;
        while(st<k&&ok)
        {
            make_bell(coad[st]);
            ++st;
        }
        for(int i=1;i<=N;++i)
            viz[i]=0;
        dfs(1);
        for(auto x: mcl){
            printf("%d ",x);
        }
        for(int i=1;i<=M;++i){
            if(smc[i] == 0){
                printf("%d ",i);
            }
        }
        printf("\n");
    }
}