CF1766C Hamiltonian Wall(线性dp)

文章提供了一个C++代码示例,用于解决在给定的2D矩阵中,通过一笔滑动方式走过所有B的问题。代码利用动态规划计算每一列中可以走过的B的最大数量,并检查是否能达到总数。如果能,输出YES,否则输出NO。
摘要由CSDN通过智能技术生成

Hamiltonian Wall - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

Problem - C - Codeforces

判断是否通过一笔滑 的方式走完 全部B

#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#include <queue>
#define x first
#define int long long
#define y second
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;
typedef pair<char,int> PCI;
typedef pair<string,int> PSI;
typedef pair<LL,LL> PLL;
//typedef __int128 i128;
typedef unsigned long long ULL;
const int N=2e5+10,INF = 1e9 ,mod = 1e9 + 7 ,P = 131;
const double eps = 1e-7;

int n,m;




void solve()
{
    cin >> n;
    string s[2];
    cin >> s[0] >> s[1];
    
    int cnt= count(s[0].begin(),s[0].end(),'B') + count(s[1].begin(),s[1].end(),'B');
    
    vector dp(2,vector<int>(n,0));// c++ 20
    vector<vector<int>> dp(2,vector<int>(n,0));//c++ 11 dp[2][n]={0}
    
    for(int j=0;j<n ;j++ )
    {
        for(int i=0;i<2;i ++ )// 判断每一列中的两行 
        {
            if(s[i][j] == 'W') continue;
            if(!j) dp[i][j] = 1;
            else if(s[i][j-1] == 'B') dp[i][j] = dp[i][j-1] + 1;
            // 可以从右边转移过来 
        }
        
        if(s[0][j] == 'B' && s[1][j] == 'B') // 一列中两行都是B,可以上下走 
        {
            int t= dp[0][j];
            dp[0][j] = max(dp[0][j],dp[1][j] + 1);
            dp[1][j] = max(dp[1][j],t + 1);
        }
        // 任何一个 地方 走过的B个数 等于 总的个数 就算是找到了 
        if(dp[0][j] == cnt || dp[1][j] == cnt)
        {
            cout << "YES\n";
            return;
        }
    }
    cout <<"NO\n";    
                
}
signed main()
{
//    freopen("1.txt","r",stdin);
    ios
    
    
    LL T=1;
    cin>>T;
    while(T -- )
    {
        solve();
    }



    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值