算法训练营第五十八天 | LeetCode 392 判断子序列、卡码网模拟美团笔试第一、二、三题(300/500有待提高)

卡码网图论更新了可以去看看,模拟笔试第四题就是深搜/广搜还不太会

LeetCode 392 判断子序列


其实就是最长公共子序列翻版

代码如下:

java 复制代码
class Solution {
    public boolean isSubsequence(String s, String t) {
        int[][] dp = new int[s.length() + 1][t.length() + 1];
        int result = 0;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s.charAt(i-1) == t.charAt(j-1))
                    dp[i][j] = Math.max(dp[i][j], dp[i-1][j-1]+1);
                else dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                if (result < dp[i][j]) result = dp[i][j];
            }
        }
        return result == s.length();
    }
}

模拟美团笔试第一题 小美的排列询问


简单模拟

代码如下:

cpp 复制代码
#include <iostream>

using namespace std;

int main() {
    int n;
    cin >> n;
    int a[n];
    for (int i = 0; i < n; i++) cin >> a[i];
    int x, y;
    cin >> x >> y;
    for (int i = 0; i < n; i++) {
        if (a[i] == x || a[i] == y) {
            if (i + 1 < n && (a[i+1] == x || a[i+1] == y) && a[i+1] != a[i]) {
                cout << "Yes" << endl;
                return 0;
            } else break;
        }
    }
    cout << "No" << endl;
}

第二题 小美走公路


简单模拟

代码如下:

cpp 复制代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    long long a[n];
    long long sum = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        sum += a[i];
    }    
    int x, y;
    cin >> x >> y;
    if (x > y) {
        long long t = y;
        y = x;
        x = t;
    }
    if (x == y) {
        cout << 0 << endl;
        return 0;
    }
    long long cost = 0;
    for (int i = x; i < y; i++) {
        cost += a[i];
    }
    cost = min(cost, sum - cost);
    cout << cost << endl;
}

第三题 小美的蛋糕切割


二维前缀和

代码如下:

cpp 复制代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    long long a[n];
    long long sum = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        sum += a[i];
    }    
    int x, y;
    cin >> x >> y;
    if (x > y) {
        long long t = y;
        y = x;
        x = t;
    }
    if (x == y) {
        cout << 0 << endl;
        return 0;
    }
    long long cost = 0;
    for (int i = x; i < y; i++) {
        cost += a[i];
    }
    cost = min(cost, sum - cost);
    cout << cost << endl;
}
相关推荐
int型码农3 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT3 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面3 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked933 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
怀旧,3 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
积极向上的向日葵3 小时前
有效的括号题解
数据结构·算法·
GIS小天3 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
_Itachi__4 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
不忘不弃4 小时前
计算矩阵A和B的乘积
线性代数·算法·矩阵
不爱写代码的玉子4 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#