hduHDU Today(Dijkstra)

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2112

RE了无数次 终于AC了。。

代码:

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#define inf 0x3f3f3f3f

using namespace std;

int n;
char start[40],ende[40];
char str[200][40];
int dis[160];
int cnt;
int e[200][200];
bool v[200];
int generateId(char a[])

{
    int i;
    for(i = 0; i < cnt; i++)
        if(strcmp(str[i], a) == 0)
            return i;
    if(i == cnt)
    {
        strcpy(str[cnt], a);
        cnt++;
        return cnt-1;
    }
}

void dijkstra()

{
    memset(v,false,sizeof v);
    for(int i = 0;i < cnt;++i)
        dis[i] = e[0][i];
    v[0] = true;
    for(int i = 0;i < cnt;++i)
    {
        int k;
        int Min = inf;
        for(int j = 0;j < cnt;++j)
        {
            if(!v[j] && dis[j] < Min)
            {
                k = j;
                Min = dis[j];
            }
        }
        if(Min == inf)
            break;
        v[k] = true;
        for(int j = 0;j < cnt;++j)
        {
            if(!v[j] && dis[j] > dis[k] + e[k][j])
            {
                dis[j] = dis[k] + e[k][j];
            }
        }
    }
}

int main()

{
    while(~scanf("%d",&n))
    {
        if(n == -1)
            break;
        for(int i = 0;i < 160;++i)
            for(int j = 0;j < 160;++j)
                 if(i == j)
                     e[i][j] = 0;
                 else
                     e[i][j] = inf;
        scanf("%s%s",start,ende);
        strcpy(str[0],start);
        strcpy(str[1],ende);
        cnt = 2;
        for(int i = 1; i <= n; ++i)
        {
            char s3[40],s4[40];
            int t;
            scanf("%s%s%d",s3,s4,&t);
            int aId = generateId(s3);
            int bId = generateId(s4);
            e[aId][bId] = e[bId][aId] = t;
        }
        //printf("cnt = %d\n",cnt );
        if(strcmp(start,ende) == 0)
        {
            printf("0\n");
            continue;
        }
        dijkstra();
        if(dis[1] != inf)
           printf("%d\n",dis[1]);
        else
            printf("-1\n");

    }
}

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