ZOJ:2750 Idiomatic Phrases Game

Dijkstra算法求最短路。

之前一直TLE于是用了优先队列用了char[],其实是

shortpath[i]=shortpath[v]+gl[v][i];

这里在gl[v][i]为无穷大即v和i无边的时候溢出了。所以要特判一下gl[v][i]不是无穷大。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#define MAXN 1050
using namespace std;
typedef  pair<int ,int>  Pair;
int gl[MAXN][MAXN];
char word[MAXN][MAXN];
int val[MAXN];
bool Match(char a[], char b[])
{
    int l=strlen(b);
    if(a[0]==b[l-4]&&a[1]==b[l-3]&&a[2]==b[l-2]&&a[3]==b[l-1])
        return true;
    else return false;
}
int main()
{
    int n;
    while(scanf("%d",&n)==1&&n)
    {
        memset(word,0,sizeof(word));
        for(int i=0; i<n; ++i)
        {
            char str[MAXN];
            scanf("%d%s",&val[i],str);
            for(int j=0; j<4; ++j)
                word[i][j]=str[j];
            int l=strlen(str);
            for(int j=l-4,k=0; j<l; ++j,++k)
                word[i][4+k]=str[j];
                word[i][8]=0;
        }
        memset(gl,0x7f,sizeof(gl));
        for(int i=0; i<n; ++i)
            for(int j=i+1; j<n; ++j)
            {
                if(Match(word[i],word[j]))
                    gl[j][i]=val[j];
                if(Match(word[j],word[i]))
                    gl[i][j]=val[i];
            }
        int shortpath[MAXN];
        memset(shortpath,0x7f,sizeof(shortpath));
        int INF=shortpath[0];
        shortpath[0]=0;
        priority_queue< Pair, vector<Pair>, greater<Pair> > pq;
        pq.push(Pair(0,0));
        while(!pq.empty())
        {
            Pair tmp=pq.top();
            pq.pop();
            int v=tmp.second;
            if(shortpath[v]<tmp.first)  continue;
            for(int i=0; i<n; ++i)
            {
                if(gl[v][i]!=INF&&shortpath[i]>shortpath[v]+gl[v][i])
                {
                    shortpath[i]=shortpath[v]+gl[v][i];
                    pq.push(Pair(shortpath[i],i));
                }
            }
        }
        if(shortpath[n-1]==INF)
            puts("-1");
        else printf("%d\n",shortpath[n-1]);
    }
    return 0;
}


 

你可能感兴趣的:(优先队列,单源最短路)