hdu 2112 HDU Today 最短路

来源:互联网 发布:淘宝提示出售假冒商品 编辑:程序博客网 时间:2024/05/15 05:17

最短路裸题。

#include<stdio.h>#include<string.h>#include<queue>#include<string>#include<iterator>#include<map>using namespace std;#define N 10055#define maxx 99999999int n, m;int vis[N], ans[N];char s[32], e[32];struct node{    int dis[300], next[300];    int num;}mat[N];void spfa(int st){    for(int i = 1; i <= n; i++) // 初始化距离          ans[i] = (i == st ? 0: maxx);       memset(vis, 0, sizeof(vis));     queue<int > q;     while(!q.empty())    q.pop();     q.push(st);     vis[st] = 1;     while(!q.empty())     {         int now = q.front();         for(int i = 0; i < mat[now].num; i++)          {             if(ans[now] + mat[now].dis[i] < ans[mat[now].next[i]])              {                  ans[mat[now].next[i]] = ans[now] + mat[now].dis[i];                  if(!vis[mat[now].next[i]]) // 这个节点松弛过且不在队列,则入队                   {                      q.push(mat[now].next[i]);                      vis[mat[now].next[i]] = 1;                    }                 }          }         q.pop();         vis[now] = 0;     }}int main(){    map<string, int> m;    char s1[32], s2[32];    while(~scanf("%d", &n) && n != -1)    {        m.clear();        bool flag = 0;        int d;        for (int i = 1; i <= n; i++ )            mat[i].num = 0;        scanf("%s%s", s, e);         if(!strcmp(s, e))         {             flag = 1;         }         m[s] = 1;         m[e] = 2;         int cnt = 3;         for(int i = 0; i < n; i++)         {             scanf("%s%*c%s%*c%d%*c", s1, s2, &d);             if(!m[s1])             {                 m[s1] = cnt++;//a             }             if(!m[s2])             {                 m[s2] = cnt++;//b             }             mat[m[s1]].next[mat[m[s1]].num] = m[s2];             mat[m[s1]].dis[mat[m[s1]].num++] = d;                          mat[m[s2]].next[mat[m[s2]].num] = m[s1];             mat[m[s2]].dis[mat[m[s2]].num++] = d;         }         if(flag)         {             printf("0\n");             continue;         }         spfa(m[s]);         if(ans[2] == maxx)         {             printf("-1\n");         }         else         printf("%d\n", ans[2]);    }    return 0;}

代码的确丑TUT

0 0
原创粉丝点击