51Nod-1510-最小化序列

本文针对一道ACM竞赛题目,采用贪心算法进行初步处理后,结合动态规划进一步优化解决方案,最终实现对数据的有效分组,以达到最小化总成本的目标。

ACM模版

描述

描述

题解

这个题,打眼一看就是贪心,然后我就贪心写了一下, WA 了三分之一,分析了一下,感觉只是贪心不行,还有 dp 搞搞才行……

首先,贪心的思路是,我们需要将数据分为 k 组,其中有 n % k 组的大小为 nk+1 ,剩下的 kn % k 组有 nk 个。这个好理解,就不多说了,接着我们要将序列排序,因为当我们这样分组时,最后结果其实就是各组最小花费的和,而各组的最小花费当然是选取若干个排序后是连续的数最佳,加减抵消后的结果就是每组最后一个数减去第一个数,当然,也就是最大的数减去最小的数。此时,剩下的问题就很明朗了,排序后的数组如何划分为上述 k 组使其和最小?这个部分自然就是动归了。

其实,这里的第二部分我们不用动归也未尝不可,用 dfs 搜索也许也是可以的,因为我们可以肯定的是,每次划分一段区间作为一组数的时候,都要贪心的从左右两侧划分,所以控制好未划分区间即可。一直到划分完后,判断一下结果是否更优,当然,这种方法并不是特别好,时间消耗可能比较高,记忆化一下能提升一些效率,但是还是不如 dp 省事儿,实在是下策。

也许,上边就是我在胡诌,并不可行吧……懒得尝试了。

代码

#include <iostream>
#include <algorithm>
#include <cstdio>

using namespace std;

const int MAXN = 3e5 + 10;
const int MAXK = 5e3 + 10;

int n, k;
int A[MAXN];
int dp[MAXK][MAXK];

template <class T>
inline bool scan_d(T &ret)
{
    char c;
    int sgn;
    if (c = getchar(), c == EOF)
    {
        return 0; //EOF
    }
    while (c != '-' && (c < '0' || c > '9'))
    {
        c = getchar();
    }
    sgn = (c == '-') ? -1 : 1;
    ret = (c == '-') ? 0 : (c - '0');
    while (c = getchar(), c >= '0' && c <= '9')
    {
        ret = ret * 10 + (c - '0');
    }
    ret *= sgn;
    return 1;
}

int main()
{
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++)
    {
        scan_d(A[i]);
    }
    sort(A, A + n);

    int t1 = n % k;
    int t2 = k - t1;
    k = n / k;

    dp[0][0] = 0;
    for (int i = 1; i <= t2; i++)
    {
        dp[i][0] = dp[i - 1][0] + A[i * k - 1] - A[(i - 1) * k];
    }
    for (int j = 1; j <= t1; j++)
    {
        dp[0][j] = dp[0][j - 1] + A[j * (k + 1) - 1] - A[(j - 1) * (k + 1)];
    }

    int k1, k2;
    for (int i = 1; i <= t2; i++)
    {
        for (int j = 1; j <= t1; j++)
        {
            k1 = (i - 1) * k + j * (k + 1);
            k2 = i * k + (j - 1) * (k + 1);
            dp[i][j] = min(dp[i - 1][j] + ((k1 + k) > n ? 0 : (A[k1 + k - 1] - A[k1])),
                           dp[i][j - 1] + ((k2 + k + 1) > n ? 0 : (A[k2 + k] - A[k2])));
        }
    }

    printf("%d\n", dp[t2][t1]);

    return 0;
}
analyzeAction(result) { const self = this; const currentAction = this.selectedActions[this.verificationStep - 1]; if (!currentAction) return; const landmarks = result.landmarks; if (!landmarks) { self.currentPrompt = '未检测到面部特征,请对准摄像头'; self.promptStatus = 'warning'; return; } // 提取必要的面部特征点集 const facePoints = landmarks.positions; if (!facePoints || facePoints.length < 68) { self.currentPrompt = '面部特征点不足,请调整姿势'; self.promptStatus = 'warning'; return; } // 计算面部中心位置 const faceCenter = { x: (facePoints[0].x + facePoints[16].x) / 2, y: (facePoints[27].y + facePoints[8].y) / 2 }; // 计算面部宽度和高度作为参考 const faceWidth = Math.abs(facePoints[16].x - facePoints[0].x); const faceHeight = Math.abs(facePoints[8].y - facePoints[27].y); // 自适应调整检测阈值(根据面部大小动态调整) const adaptiveThreshold = { nod: Math.max(6, faceHeight * 0.12), // 点头阈值(基于面部高度百分比) shake: Math.max(8, faceWidth * 0.15), // 摇头阈值 eye: Math.max(3, faceHeight * 0.05), // 眨眼阈值 mouth: Math.max(4, faceWidth * 0.1) // 张嘴阈值 }; // 1. 点头检测(基于鼻尖和下巴的相对位置变化) if (currentAction.type === 'nod') { // 提取鼻尖(30)和下巴(8)关键点 const noseTip = facePoints[30]; const chin = facePoints[8]; const currentDistance = Math.abs(noseTip.y - chin.y); // 垂直距离(y轴向下为正) // 初始化基准值(取前3帧的平均距离作为静止基准) if (!self.nodInitialDistance) { self.nodDistanceHistory.push(currentDistance); if (self.nodDistanceHistory.length >= 3) { // 计算初始基准值(前3帧平均) self.nodInitialDistance = self.nodDistanceHistory.reduce((a, b) => a + b, 0) / 3; self.nodDistanceHistory = []; // 重置历史,开始记录变化 self.currentPrompt = '请缓慢点头(上下移动)'; } return; } // 计算当前距离与基准值的变化率(正为低头,负为抬头) const changeRate = (currentDistance - self.nodInitialDistance) / self.nodInitialDistance; // 记录变化历史(仅保留最近5帧,约400ms) self.nodDistanceHistory.push({ time: Date.now(), changeRate }); if (self.nodDistanceHistory.length > 5) self.nodDistanceHistory.shift(); // 检测是否有完整的点头动作:先低头(变化率≥15%)再抬头(变化率≤-5%) const hasDown = self.nodDistanceHistory.some(item => item.changeRate >= self.nodRequiredChange); const hasUp = self.nodDistanceHistory.some(item => item.changeRate <= -0.05); const durationValid = self.nodDistanceHistory.length >= 5 && (self.nodDistanceHistory[4].time - self.nodDistanceHistory[0].time) >= self.nodMinDuration; console.log(hasDown, hasUp, durationValid,'是否有点头抬头') if (hasDown && hasUp && durationValid) { // 完成有效点头动作 self.currentPrompt = '点头完成!'; self.promptStatus = 'success'; self.goToNextStep(); } else { // 未完成时提示 self.currentPrompt = '请缓慢点头(上下移动)'; self.promptStatus = 'warning'; } } // 2. 摇头检测(基于左右脸边界点的相对位置变化) else if (currentAction.type === 'shake') { const noseBridge = facePoints[27]; // 鼻梁关键点(水平位置参考) const currentX = noseBridge.x; const currentTime = Date.now(); // 1. 记录当前位置到历史数据(只保留最近10条,约800ms内的记录,与检测频率匹配) this.shakeHistory.push({ x: currentX, time: currentTime }); if (this.shakeHistory.length > 10) { this.shakeHistory.shift(); // 移除最旧的记录 } // 2. 历史数据不足时,不判定 if (this.shakeHistory.length < 5) { this.currentPrompt = '请左右摇头...'; this.promptStatus = 'warning'; return; } // 3. 分析历史数据,判断是否有“左→右”或“右→左”的摆动 const firstX = this.shakeHistory[0].x; // 最早记录的x const lastX = this.shakeHistory[this.shakeHistory.length - 1].x; // 最新记录的x const timeElapsed = currentTime - this.shakeHistory[0].time; // 动作持续时间 // 计算左右摆动的总距离(绝对值) const totalDistance = Math.abs(lastX - firstX); // 4. 判断是否完成一次完整摇头动作: // - 总距离超过最小阈值(确保有明显摆动) // - 时间在合理范围内(不超过最大时间) // - 方向发生反转(先左后右或先右后左) const isLeftToRight = firstX < lastX - this.shakeMinDistance; // 先左后右 const isRightToLeft = firstX > lastX + this.shakeMinDistance; // 先右后左 const isValidTime = timeElapsed <= this.shakeMaxTime; if ((isLeftToRight || isRightToLeft) && totalDistance >= this.shakeMinDistance && isValidTime) { // 判定为完成摇头动作 this.updateActionProgress(true, 'shake'); } else { // 未完成,提示继续 this.updateActionProgress(false, 'shake'); // 若超时未完成,重置历史记录(避免累计无效数据) if (timeElapsed > this.shakeMaxTime) { this.shakeHistory = []; this.currentPrompt = '摇头动作太慢,请重试...'; } } } // 眨眼动作增强逻辑 else if (currentAction.type === 'eye') { // 计算左右眼EAR并取平均 const leftEyeIndices = [36, 37, 38, 39, 40, 41]; const rightEyeIndices = [42, 43, 44, 45, 46, 47]; const leftEAR = this.calculateEyeAspectRatio(facePoints, leftEyeIndices); const rightEAR = this.calculateEyeAspectRatio(facePoints, rightEyeIndices); const currentEAR = (leftEAR + rightEAR) / 2; // 记录EAR历史(保留最近8帧,约640ms) self.blinkEARHistory.push({ time: Date.now(), ear: currentEAR }); if (self.blinkEARHistory.length > 12) self.blinkEARHistory.shift(); // 状态机:检测完整眨眼过程(睁→闭→睁) switch (self.blinkState) { case 'open': // 从睁眼状态进入闭眼状态(EAR从>0.3降到<0.2) if (currentEAR < self.blinkCloseThreshold && self.blinkEARHistory.some(item => item.ear > self.blinkOpenThreshold)) { self.blinkState = 'closing'; } break; case 'closing': // 允许EAR在阈值附近小幅波动(增加±0.02容错) const hasClosed = self.blinkEARHistory.some(item => item.ear < self.blinkCloseThreshold - 0.02); const hasOpened = currentEAR > self.blinkOpenThreshold + 0.02; if (hasOpened && hasClosed) { // 持续时间检查保持不变 const firstCloseTime = self.blinkEARHistory.find(item => item.ear < self.blinkCloseThreshold)?.time; const lastOpenTime = self.blinkEARHistory[self.blinkEARHistory.length - 1].time; if (firstCloseTime && (lastOpenTime - firstCloseTime) >= self.blinkMinDuration) { self.currentPrompt = '眨眼完成!'; self.promptStatus = 'success'; self.goToNextStep(); } else { self.blinkState = 'open'; } } break; } // 未完成时提示 if (self.blinkState !== 'success') { self.currentPrompt = '请缓慢眨眼(稍用力)'; self.promptStatus = 'warning'; } } // 4. 张嘴检测(新增) else if (currentAction.type === 'mouth') { // 上嘴唇关键点(索引51)和下嘴唇关键点(索引57) const upperLip = facePoints[51]; const lowerLip = facePoints[57]; // 计算嘴唇垂直距离 const mouthOpenDistance = Math.abs(upperLip.y - lowerLip.y); // 计算嘴部区域高度作为参考(上唇到下巴距离的1/3) const mouthReference = Math.abs(facePoints[27].y - facePoints[8].y) / 3; // 张嘴判定:距离超过参考值的60% const isMouthOpen = mouthOpenDistance > mouthReference * 0.6; if (isMouthOpen) { this.mouthConsecutiveFrames++; // 要求连续3帧检测到张嘴 if (this.mouthConsecutiveFrames >= this.mouthRequiredFrames) { this.updateActionProgress(true, 'mouth'); } } else { this.mouthConsecutiveFrames = Math.max(0, this.mouthConsecutiveFrames - 1); this.updateActionProgress(false, 'mouth'); } console.log(`张嘴检测:距离=${mouthOpenDistance.toFixed(2)}, 参考值=${(mouthReference * 0.6).toFixed(2)}, 是否张嘴=${isMouthOpen}`); } }, 眨眼和点头换用新的方法,现在的判断太不行了
最新发布
07-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值