51nod 1445 变色DNA(最短路变形)

时间:2023-03-09 06:20:38
51nod 1445 变色DNA(最短路变形)

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1445

题意:

51nod 1445 变色DNA(最短路变形)

思路:

挺好的一道题目,如果$colormap[i][j]$为'Y',那么这条边的代价就是前面Y出现的次数。也就是说前面必须得都破坏了这样才能轮到这条边,这样一来跑一遍最短路即可。

 #include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn=+;
const int mod=1e9+; int n;
int tot;
char s[];
int head[];
int d[];
bool done[]; struct node
{
int v,w,next;
}edge[maxn]; struct HeapNode
{
int d,u;
HeapNode(){}
HeapNode(int d, int u):d(d),u(u){}
bool operator < (const HeapNode& rhs) const
{
return d>rhs.d;
}
}; void addEdge(int u, int v, int w)
{
edge[tot].v=v;
edge[tot].w=w;
edge[tot].next=head[u];
head[u]=tot++;
} void dijkstra(int s)
{
priority_queue<HeapNode> Q;
for(int i=;i<n;i++) d[i]=INF;
d[s]=;
memset(done,,sizeof(done));
Q.push(HeapNode(,s));
while(!Q.empty())
{
HeapNode x=Q.top(); Q.pop();
int u=x.u;
if(done[u]) continue;
done[u]=true;
for(int i=head[u];i!=-;i=edge[i].next)
{
int v=edge[i].v;
if(d[v]>d[u]+edge[i].w)
{
d[v]=d[u]+edge[i].w;
Q.push(HeapNode(d[v],v));
}
}
}
} int main()
{
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
tot=;
memset(head,-,sizeof(head));
scanf("%d",&n);
for(int i=;i<n;i++)
{
int cnt=;
scanf("%s",s);
for(int j=;j<n;j++)
if(s[j]=='Y') {addEdge(i,j,cnt);cnt++;}
}
dijkstra();
if(d[n-]==INF) puts("-1");
else printf("%d\n",d[n-]);
}
return ;
}