多阶段决策问题----多段图的最短路Uva116 Unidirectional TSP

注意只有一列的情况

要求字典序很小就先遍历行号小的,再遍历行号大的

样例试不出来的bug真是令人头禿

按照我代码习惯,我喜欢在开始初始化,导致n=1的情况下,for循环进不去。。。

先看数据先看数据先看数据,先想特例先想边界

这个和数塔也挺像的,肯定要从最后一列往前去累加

#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
int mat[15][110];
LL dp[15][110];
int nxt[15][110];
int m,n;
int main()
{
   // freopen("in.txt","r",stdin);
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        int ans=INF,first=0;
        memset(dp,INF,sizeof(dp));
        memset(nxt,0,sizeof(nxt));
        for(int i=1;i<=m;++i)
            for(int j=1;j<=n;++j)
            scanf("%d",&mat[i][j]);
        for(int i=1;i<=m;++i)
            dp[i][n]=mat[i][n];
        if(n==1)
        {
            for(int i=1;i<=m;++i)
            {
                if(dp[i][1]<ans)
                {
                    ans=dp[i][1];
                    first=i;
                }
            }
        }
        else                                      //只有一列的时候进不来
        {
                for(int j=n-1;j>=1;--j)                 //序
            {
                for(int i=1;i<=m;++i)
                {
                    //三个比较的思路很好想,取min即可
                    int row[3]={i-1,i,i+1};
                    if(i==1) row[0]=m;             //把行数写成n了,傻子啊
                    if(i==m) row[2]=1;
                    sort(row,row+3);                //巧妙
                    for(int k=0;k<3;++k)
                    {
                        int v=dp[row[k]][j+1]+mat[i][j];
                        if(v<dp[i][j])
                        {
                            dp[i][j]=v;
                            nxt[i][j]=row[k];
                        }

                    }
                    //可以从第一列任意一行开始
                    if(j==1&&dp[i][j]<ans)
                    {
                        ans=dp[i][j];
                        first=i;
                    }
                }

            }
        }

        printf("%d",first);
        for(int i=nxt[first][1],j=2;j<=n;i=nxt[i][j],j++)
            printf(" %d",i);
        printf("\n%d\n",ans);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The code you provided defines a named tuple `Hypothesis` with two fields, `value` and `score`. This is a convenient way to store and manipulate hypotheses in the context of sequence-to-sequence models. The `NMT` class is a PyTorch module that implements a simple neural machine translation model. It consists of a bidirectional LSTM encoder, a unidirectional LSTM decoder, and a global attention mechanism based on Luong et al. (2015). Here's a breakdown of the code: ```python from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F Hypothesis = namedtuple('Hypothesis', ['value', 'score']) class NMT(nn.Module): def __init__(self, src_vocab_size, tgt_vocab_size, emb_size, hidden_size): super(NMT, self).__init__() self.src_embed = nn.Embedding(src_vocab_size, emb_size) self.tgt_embed = nn.Embedding(tgt_vocab_size, emb_size) self.encoder = nn.LSTM(emb_size, hidden_size, bidirectional=True) self.decoder = nn.LSTMCell(emb_size + hidden_size, hidden_size) self.attention = nn.Linear(hidden_size * 2, hidden_size) self.out = nn.Linear(hidden_size, tgt_vocab_size) self.hidden_size = hidden_size def forward(self, src, tgt): batch_size = src.size(0) src_len = src.size(1) tgt_len = tgt.size(1) # Encode the source sentence src_embedded = self.src_embed(src) encoder_outputs, (last_hidden, last_cell) = self.encoder(src_embedded) # Initialize the decoder states decoder_hidden = last_hidden.view(batch_size, self.hidden_size) decoder_cell = last_cell.view(batch_size, self.hidden_size) # Initialize the attention context vector context = torch.zeros(batch_size, self.hidden_size, device=src.device) # Initialize the output scores outputs = torch.zeros(batch_size, tgt_len, self.hidden_size, device=src.device) # Decode the target sentence for t in range(tgt_len): tgt_embedded = self.tgt_embed(tgt[:, t]) decoder_input = torch.cat([tgt_embedded, context], dim=1) decoder_hidden, decoder_cell = self.decoder(decoder_input, (decoder_hidden, decoder_cell)) attention_scores = self.attention(encoder_outputs) attention_weights = F.softmax(torch.bmm(attention_scores, decoder_hidden.unsqueeze(2)).squeeze(2), dim=1) context = torch.bmm(attention_weights.unsqueeze(1), encoder_outputs).squeeze(1) output = self.out(decoder_hidden) outputs[:, t] = output return outputs ``` The `__init__` method initializes the model parameters and layers. It takes four arguments: - `src_vocab_size`: the size of the source vocabulary - `tgt_vocab_size`: the size of the target vocabulary - `emb_size`: the size of the word embeddings - `hidden_size`: the size of the encoder and decoder hidden states The model has four main components: - `src_embed`: an embedding layer for the source sentence - `tgt_embed`: an embedding layer for the target sentence - `encoder`: a bidirectional LSTM encoder that encodes the source sentence - `decoder`: a unidirectional LSTM decoder that generates the target sentence The attention mechanism is implemented in the `forward` method. It takes two arguments: - `src`: the source sentence tensor of shape `(batch_size, src_len)` - `tgt`: the target sentence tensor of shape `(batch_size, tgt_len)` The method first encodes the source sentence using the bidirectional LSTM encoder. The encoder outputs and final hidden and cell states are stored in `encoder_outputs`, `last_hidden`, and `last_cell`, respectively. The decoder is initialized with the final hidden and cell states of the encoder. At each time step, the decoder takes as input the embedded target word and the context vector, which is a weighted sum of the encoder outputs based on the attention scores. The decoder output and hidden and cell states are updated using the LSTMCell module. The attention scores are calculated by applying a linear transform to the concatenated decoder hidden state and encoder outputs, followed by a softmax activation. The attention weights are used to compute the context vector as a weighted sum of the encoder outputs. Finally, the decoder hidden state is passed through a linear layer to produce the output scores for each target word in the sequence. The output scores are stored in the `outputs` tensor and returned by the method.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值