hdu2112: HDU Today

hdu2112: http://acm.hdu.edu.cn/showproblem.php?pid=2112
题意:求最短路,输入的各个节点是用字符串表示的。 解法:Dijkstra,将字符串转为编号,用int数组存入邻接矩阵 code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int inf=1<<29;
char v[200][50];
int w[200][200],vis[200],d[200];
int main()
{
    int n,t,i,j,k,q,h,u;
    char s[50],e[50],a[50],b[50];
    while(1)
    {
        memset(vis,0,sizeof(vis));
        scanf("%d",&n);
        if(n==-1)break;
        for(i=0;i<200;i++)
            for(j=0;j<200;j++)
                w[i][j]=inf;
        scanf("%s%s",s,e);
        strcpy(v[0],s);
        strcpy(v[1],e);
        k=2;
        for(i=0;i<n;i++)
        {
            scanf("%s%s%d",a,b,&t);
            for(j=0;j<k;j++)
            {
                if(strcmp(a,v[j])==0)
                {
                    q=j;
                    break;
                }
            }
            if(j==k)
            {
                strcpy(v[k],a);
                q=k;
                k++;
            }
            for(j=0;j<k;j++)
            {
                if(strcmp(b,v[j])==0)
                {
                    h=j;
                    break;
                }
            }
            if(j==k)
            {
                strcpy(v[k],b);
                h=k;
                k++;
            }
            if(t<w[q][h])
                {w[q][h]=t;w[h][q]=t;} 
        }
        if(strcmp(s,e)==0)
        {
            printf("0\n");
            continue;
        }
        d[0]=0;
        for(i=1;i<k;i++)
            d[i]=w[0][i];
        for(i=0;i<k;i++)     //Dijkstra
        {
            int min=inf;
            for(j=0;j<k;j++)
            {
                if(!vis[j]&&d[j]<min)
                {
                    min=d[j];
                    u=j;
                }
            }
            vis[u]=1;
            for(j=0;j<k;j++)
            {
                if(!vis[j]&&d[j]>d[u]+w[u][j])
                    d[j]=d[u]+w[u][j];
            }
        }
        if(d[1]==inf)
            printf("-1\n");
        else
            printf("%d\n",d[1]);
    }
}
/*
input:
6
xiasha westlake
xiasha station 60
xiasha ShoppingCenterofHangZhou 30
station westlake 20
ShoppingCenterofHangZhou supermarket 10
xiasha supermarket 50
supermarket westlake 10
-1
output:
50
*/ 

posted on 2012-07-25 16:50  acmer-jun  阅读(158)  评论(0编辑  收藏  举报

导航