首页 > 代码库 > 51nod 1445 变色DNA(dij)

51nod 1445 变色DNA(dij)

题目链接:51nod 1445 变色DNA

看了相关讨论再去用最短路:val[i][j]之间如果是‘Y’,说明i可以到达j,并且i到达j的代价是i那行 1到j-1 里面‘Y’的数量。

最后,求 0到n-1的最短路。

感觉读懂了题意就真的简单了。。

技术分享
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<vector>
 5 #include<queue>
 6 #define CLR(a,b) memset((a),(b),sizeof((a)))
 7 using namespace std;
 8 const int inf = 0x3f3f3f3f;
 9 const int N = 51;
10 int d[N], vis[N];
11 char mp[N];
12 int n;
13 struct qnode{
14     int v, c;
15     qnode(int _v = 0,int _c = 0):v(_v),c(_c) {}
16     bool operator < (const qnode &r)const{
17         return r.c < c;
18     }
19 };
20 vector<int>E[N];
21 void dij(){
22     priority_queue<qnode>q;
23     for(int i = 1; i <= n; ++i){
24         d[i] = inf;
25         vis[i] = 0;
26     }
27     d[1] = 0;
28     q.push(qnode(1, 0));
29     while(!q.empty()){
30         qnode t = q.top(); q.pop();
31         int u = t.v;
32         if(vis[u])
33             continue;
34         vis[u] = 1;
35         for(int i = 0; i < E[u].size(); ++i){
36             int v = E[u][i];
37             if(!vis[v] && d[u] + i < d[v]){
38                 d[v] = d[u] + i;
39                 q.push(qnode(v, d[v]));
40             }
41         }
42     }
43 }
44 int main(){
45     int t, i, j;
46     scanf("%d", &t);
47     while(t--){
48         scanf("%d", &n);
49         for(i = 0; i < N; ++i) E[i].clear();
50         for(i = 1; i <= n; ++i){
51             scanf("%s",mp+1);
52             for(j = 1; j <= n; ++j)
53                 if(mp[j] == Y)
54                     E[i].push_back(j);
55         }
56         dij();
57         printf("%d\n", d[n]==inf?-1:d[n]);
58     }
59     return 0;
60 }
View Code

 

51nod 1445 变色DNA(dij)