51nod 1445 变色DNA dijkstra变形

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37428263/article/details/88765671

点击打开链接

注意链式前向星的应用

//dij
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>PII;
const int maxn=50+5;
const int maxe=2500+5;
const int INF=0x3f3f3f3f;
struct Edge{
    int next,to,dist;
};
Edge edges[maxe];
int head[maxn],cnt,d[maxn];
bool done[maxn];
void add_edge(int u,int v,int weight)
{
    edges[++cnt].next=head[u];                  //注意这里必须是++cnt
    edges[cnt].to=v;
    edges[cnt].dist=weight;
    head[u]=cnt;
}
void dijkstra(int st,int en)
{
    memset(d,INF,sizeof(d));
    memset(done,false,sizeof(done));
    priority_queue<PII,vector<PII>,greater<PII> >pq;
    while(!pq.empty()) pq.pop();
    d[st]=0;
    //cout<<d[en]<<endl;
    pq.push(PII(d[st],st));
    while(!pq.empty())
    {
        PII k=pq.top();
        pq.pop();
        if(done[k.second]) continue;
        done[k.second]=true;
        if(k.second==en) return;
        for(int i=head[k.second];i!=0;i=edges[i].next)
        {
            if(!done[edges[i].to]&&d[edges[i].to]>d[k.second]+edges[i].dist)
            {
                d[edges[i].to]=d[k.second]+edges[i].dist;
                pq.push(PII(d[edges[i].to],edges[i].to));
            }
        }
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        cnt=0;
        memset(head,0,sizeof(head));
        int n;
        scanf("%d",&n);
        char s[maxn][maxn];
        for(int i=0;i<n;i++)
        {
            scanf("%s",&s[i]);
            int num=0;
            for(int j=0;j<n;j++)
            {
                if(s[i][j]=='Y') {
                    add_edge(i,j,num);
                    num++;
                }
            }
        }
        dijkstra(0,n-1);
        if(d[n-1]==INF) printf("-1\n");
        else printf("%d\n",d[n-1]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37428263/article/details/88765671