Sicily1031. Campus

最短路径问题

// Problem#: 1031
// Submission#: 1165830
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<string>
#include<cstring>
using namespace std;

int road[205][205];
int len[205];
int found[205];

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
    for(int i=0;i<205;i++)
        for(int j=0;j<205;j++)
            road[i][j]=1000000;
    memset(len,1000000,sizeof(len));
    memset(found,0,sizeof(found));
    int roadnum;
    cin>>roadnum;
    string a[300];
    string beg,end;
    int le,count=0,x,y;
    for(int i=0;i<roadnum;i++)
    {
        cin>>beg>>end>>le;
        int ok1=0,ok2=0;
        for(int i=0;i<count;i++)
        {
            if(beg==a[i])
            {
                ok1=1;
                x=i;
            }
            if(end==a[i])
            {
                ok2=1;
                y=i;
            }
        }
        if(!ok1)
        {
            a[count++]=beg;
            x=count-1;
        }
        if(!ok2)
        {
            a[count++]=end;
            y=count-1;
        }
        road[y][x]=road[x][y]=le;
    }
    string beg1,end1;
    int source=-1,end2=-1;
    cin>>beg1>>end1;
    if(beg1==end1)
    {
        cout<<0<<endl;
        continue;
    }
    for(int i=0;i<count;i++)
    {
        if(a[i]==beg1)
            source = i;
        if(a[i]==end1)
            end2 = i;
    }
    if(source==-1||end2==-1)
    {
        cout<<-1<<endl;
        continue;
    }
    for(int i=0;i<count;i++)
    {
        len[i]=road[source][i];
    }
    len[source]=0;
    found[source]=1;
    int num;
    for(int i=0;i<count;i++)
    {
        int min=1000000;
        for(int i=0;i<count;i++)
            if(!found[i])
                if(len[i]<min)
                {
                    num=i;
                    min=len[i];
                }
        found[num]=1;
        for(int i=0;i<count;i++)
        {
            if(!found[i])
                if(min+road[num][i]<len[i])
                    len[i]=min+road[num][i];
        }
    }
    if(!found[end2])
        cout<<-1<<endl;
    else
        cout<<len[end2]<<endl;
    }
    return 0;
}                                

你可能感兴趣的:(String,sun)