Tuesday, May 24, 2011

341 - Non-Stop Travel

#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#define M 12
#define MAXINT 2147483640
using namespace std;

int G[M][M],Path[M];
int DjKastra(int,int,int);
void PrintPath(int);

int main()
{
    int t,n,x,y,z,i,j,k=1,c;
    //freopen("in.txt","r",stdin);

    while(scanf("%d",&t)&&t)
    {
        memset(G,-1,sizeof(G));
        memset(Path,0,sizeof(Path));
        for(x=1;x<=t;x++)
        {
            scanf("%d",&n);
            for(j=0;j<n;j++)
            {
                scanf("%d%d",&y,&z);
                G[x][y]=z;
            }
        }

        scanf("%d%d",&x,&y);
        c = DjKastra(x,y,t);
        printf("Case %d: Path = ",k++);
        PrintPath(y);
        printf("%d; %d second delay\n",y,c);
    }
    return 0;
}

int DjKastra(int x,int y,int n)
{
    priority_queue<pair<int,int> >Q;
    pair <int,int> tmp;
    int i, j,d[M];
    bool Visited[M];
   
    for (i=1; i<=n; i++)
    {
        d[i] = MAXINT;
        Path[i] = -1;
        Visited[i] = false;
    }
   
    d[x] = 0;
    Q.push(pair <int,int>(d[x],x));
   
    while(!Q.empty())
    {
        tmp = Q.top(); 
        Q.pop();
        i = tmp.second;
        if(!Visited[i])
        {
            Visited[i] = true;
            for (j = 1; j<=n; j++)
                if (!Visited[j] && G[i][j]>=0 && d[i] + G[i][j] < d[j])
                {
                    d[j] = d[i] + G[i][j];
                    Path[j] = i;
                    Q.push(pair <int,int>(-d[j], j));
                }
        }
    }
    return d[y];
}


void PrintPath(int y)
{
    if(Path[y]== -1)
    {
        return;
    }
    PrintPath(Path[y]);
    printf("%d ",Path[y]);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.