hdu 2112 HDU Today

主要就是把名字转化成为数字顶点,建图,然后Dijkstra解决

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int MAXN = 155;
const int INF = 100000000;

int Edge[MAXN][MAXN];
int dist[MAXN];
int S[MAXN];
int num;
void Dijkstra( int v0 )
{
    int i, j, k;
    for(i = 0; i < num; ++i)
    {
        dist[i] = Edge[v0][i];
        S[i] = 0;
    }
    S[v0] = 1;
    dist[v0] = 0;

    for(i = 0; i < num; ++i)
    {
        int min = INF;
        int u = v0;
        for(j = 0; j < num; ++j)
        {
            if( !S[j] && dist[j] < min )
            {
                min = dist[j];
                u = j;
            }
        }

        if(min == INF)
            break;
        S[u] = 1;
        for(k = 0; k < num; ++k)
        {
            if( !S[k] && Edge[u][k] < INF && dist[k] > dist[u] + Edge[u][k])
                dist[k] = dist[u] + Edge[u][k];
        }
    }

}

int main()
{
    char name[MAXN][35];
    char str1[35], str2[35];
    int num1, num2,t;
    int i,j;
    int N;
    while( cin>>N )
    {

        for(i = 0; i < MAXN; ++i)
        {
            for(j = 0; j < MAXN; ++j)
            {
                Edge[i][j] = INF;
            }
        }

        if( N == -1 )
            break;
        cin>>name[0]>>name[1];
        num = 2;
        for(i = 0; i < N; ++i)
        {
           scanf("%s %s %d",str1,str2,&t);
            for(j = 0; j < num; j++)
                if(strcmp(str1, name[j]) == 0)
                {
                    num1 = j;
                    break;
                }

            if(j == num)
            {
                strcpy(name[num++], str1);
                num1 = num - 1;
            }
            for(j = 0; j < num; j++)
                if(strcmp(str2, name[j]) == 0)
                {
                    num2 = j;
                    break;
                }

            if(j == num)
            {
                strcpy( name[num++], str2);
                num2 = num - 1;
            }

            if(Edge[num1][num2] > t)
                Edge[num1][num2] = t;
            if(Edge[num2][num1] > t)
                Edge[num2][num1] = t;
        }

        if(strcmp(name[0] , name[1]) == 0)
            cout<<"0"<<endl;
        else
        {
            Dijkstra( 0 );
            if(dist[1] >= INF)
                cout<<"-1"<<endl;
            else
                cout<<dist[1]<<endl;
        }
    }
    return 0;
}


 

你可能感兴趣的:(最短路径,dijkstra)