51nod —1445 變色DNA — 最短路徑
阿新 • • 發佈:2018-11-11
題目連結:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1445
題意:一隻狼有一個對應的基因變色矩陣-矩陣中 colormap[i][j] = 'Y' 代表狼從顏色 i 變成 顏色 j,如果能變色就一定變色,但是會盡量往標號小的顏色變化。現在狼的基因顏色是 0,它想變成 N-1,你可以花費 1 的代價,將狼的變色矩陣中的某一個 colormap[i][j]='Y' 改變成 colormap[i][j]='N'。問至少花費多少總代價改變狼的基因,讓狼按它的變色策略可以從顏色0經過若干天的變色變成顏色N-1。如果一定不能變成 N-1,則輸出 -1.
解題思路(建圖模型):
1、colormap[i][j] = 'Y',相當於 i 可達 j,從 0 想變成 N-1 最小花費,相當於 0 到 N-1 的最短路。
2、題中說到能變色肯定變色且儘量變成標號小的顏色,所以其中每條可達邊 i-j 的花費為當前行中 j 之前的可變色的基因個數。
AC 程式碼如下:這題用vector會更好寫,更快,我使用前向星存圖純屬個人為了熟悉前向星存圖。
#include<bits/stdc++.h> using namespace std; #define runfile freopen("E:/Code/CB/Root/data.txt", "r", stdin) #define stopfile fclose(stdin) const int maxn = 100; const int maxm = 1e4; const int INF = 0x3f3f3f3f; const int MOD = 998244353; int n,m,u[maxm],v[maxm],w[maxm],first_n[maxn],follow_m[maxm],dis[maxn],vis[maxn]; //fisrt_n儲存以每個頂點為起點的其中一條邊的編號‘i’,以便列舉所有的邊 //follow_m儲存“編號為 i 的邊” 的 “前一條邊” 的編號,以防邊的丟失 struct node{ int v,cost; node(int _v, int _cost) : v(_v), cost(_cost){} bool operator < (const node &a) const{ return cost > a.cost;//在優先佇列中,這表示從小優先。 } }; void init() { m = 0; for(int i = 0; i < n; i++) { first_n[i] = -1; dis[i] = INF; vis[i] = 0; } } void add_edge(int from, int to, int cost) { u[m] = from; v[m] = to; w[m] = cost; follow_m[m] = first_n[from]; first_n[from] = m; m++; } int dijstra(int s) { priority_queue <node> q; q.push(node(s, 0)); dis[s] = 0; while(!q.empty()) { node now = q.top(); q.pop(); if(vis[now.v]) continue; vis[now.v] = 1; // cout<<now.v<<"*"<<endl; for(int i = first_n[now.v]; i != -1; i = follow_m[i]) { int to = v[i]; if(!vis[to] && w[i] + now.cost < dis[to]) { dis[to] = w[i] + now.cost; q.push(node(to, dis[to])); } } } return dis[n-1] == INF ? -1 : dis[n-1]; } int main() { // runfile; ios::sync_with_stdio(false); int T; char c[maxn]; scanf("%d", &T); while(T--) { scanf("%d", &n); init(); for(int i = 0; i < n; i++) { int sumy = 0; scanf("%s", &c); for(int j = 0; j < n; j++) { if(c[j] == 'Y') { add_edge(i, j, sumy); sumy++; } } } int ans = dijstra(0); printf("%d\n",ans); } // stopfile; return 0; }