位运算|拆分贪心

lcp63

遍历矩形边界的空位置,模拟小球按指定步数和方向规则移动

判断是否能到达目标点O,收集所有符合条件的起始位置

++'W'
d = (d + 3) % 4; // 逆时针转
++

抽象出检查函数复用

check(0, j, 1, num, plate))

ans.push_back({0, j});

#include <vector>

#include <string>

using namespace std;

class Solution {

private:

// 右下左上(顺时针)

const int DIRS42 = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

int m, n;

bool check(int x, int y, int d, int num, const vector<string>& plate) {

int left = num;

while (platexy != 'O') {

if (left == 0) return false;

if (platexy == ++'W')
d = (d + 3) % 4; // 逆时针转
++

else if (platexy == 'E')

d = (d + 1) % 4; // 顺时针转

x += DIRSd0;

y += DIRSd1;

if (x < 0 || x >= m || y < 0 || y >= n)

return false;

left--;

}

return true;

}

public:

vector<vector<int>> ballGame(int num, vector<string>& plate) {

m = plate.size();

n = plate0.size();

vector<vector<int>> ans;

// 检查上边(除首尾)

for (int j = 1; j < n - 1; j++) {

if (plate0j == '.' && ++check(0, j, 1, num, plate)) {
ans.push_back({0, j});
++

}

}

// 检查下边

for (int j = 1; j < n - 1; j++) {

if (platem - 1j == '.' && check(m - 1, j, 3, num, plate)) {

ans.push_back({m - 1, j});

}

}

// 检查左边

for (int i = 1; i < m - 1; i++) {

if (platei0 == '.' && check(i, 0, 0, num, plate)) {

ans.push_back({i, 0});

}

}

// 检查右边

for (int i = 1; i < m - 1; i++) {

if (platein - 1 == '.' && check(i, n - 1, 2, num, plate)) {

ans.push_back({i, n - 1});

}

}

return ans;

}

};

lc2835

给一个全是2的幂的非负整数数组和目标值,可将数组中大于1的元素拆成两个其1/2的数(算一次操作)

求让数组存在和为目标值的子序列的最少操作次数,无法实现则返回-1

统计数组元素的二进制幂次计数,

累加幂次和并与目标值二进制分段比对,++不足时拆分更大幂次元素补充++

统计拆分操作次数得到最小操作数

class Solution {

public:

int minOperations(vector<int>& nums, int target) {

if (accumulate(nums.begin(), nums.end(), 0LL) < target) {

return -1;

}

int cnt31{};

for (int x : nums) {

cnt__builtin_ctz(x)++;

}

int ans = 0, i = 0;

long long s = 0;

while ((1LL << i) <= target) {

s += (long long) cnti << i;

int mask = (1LL << ++i) - 1;

if (s >= (target & mask)) {

continue;

}

ans++; // 一定要找更大的数操作

for (; cnti == 0; i++) {

ans++; // 还没找到,继续找更大的数

}

}

return ans;

}

};

相关推荐
qq7422349849 分钟前
从“感知”到“决断”:测评百度伐谋产业决策智能体的端到端推理与行动机制
人工智能·算法·百度·大模型·运筹优化
huohaiyu1 小时前
深入解析Java垃圾回收机制
java·开发语言·算法·gc
浮芷.1 小时前
鸿蒙PC端 TTS 并发调用问题详解:资源竞争与队列管理
算法·华为·开源·harmonyos·鸿蒙·鸿蒙系统
装不满的克莱因瓶1 小时前
掌握感知器的学习原理
人工智能·python·神经网络·算法·ai·卷积神经网络
Lsk_Smion1 小时前
力扣实训 _ [994].腐烂的橘子/图论
算法·leetcode·图论
轻微的风格艾丝凡1 小时前
两电平三相VSC整流模式从不控整流平滑切换至有源整流调试记录
算法·dsp·c2000
dongf20192 小时前
R语言KNN算法
算法·数据分析·r语言
小O的算法实验室2 小时前
2025年IEEE TASE,基于双层耦合平均场博弈的大规模智能体集成任务分配与轨迹规划
人工智能·算法·机器学习
8Qi82 小时前
LeetCode 337:打家劫舍 III(House Robber III)—— 题解 ✅
算法·leetcode·二叉树·动态规划
地平线开发者2 小时前
从 INT64 Div 算子约束到 Cast 修复全流程
算法