51nod —1445 变色DNA — 最短路径

题目链接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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值