51Nod1215 数组的宽度

本文介绍了一种使用单调栈解决特定求和问题的方法。通过计算每个元素左侧和右侧最近的大于该元素值的位置来确定其贡献值,最终得出总和。文章提供了完整的代码实现。

题目看这里

各种求和最好玩的啦

看到题目就应该知道要单独考虑每个元素的贡献

那么一个元素i的贡献肯定是a[i]*(l[i]-i)*(i-r[i]),这里l,r分别表示左边和右边第一个比i大的数的位置

最大值部分的贡献算完了最小值是类似的

考虑怎么求这个l和r,直接上单调栈就可以了

(code很难看当时不知道在想什么写成这样)

#pragma GCC opitmize("O3")
#pragma G++ opitmize("O3")
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 50010
using namespace std;
int n,v[N],l[N],r[N],s[N],t; long long ans=0;
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%d",v+i);
    for(int i=1;i<=n;s[++t]=i++)
    for(;t&&v[i]>v[s[t]];--t) r[s[t]]=i;
    for(;t;--t) r[s[t]]=n+1;
    for(int i=n;i;s[++t]=i--)
    for(;t&&v[i]>=v[s[t]];--t) l[s[t]]=i;
    for(;t;--t) l[s[t]]=0;
    for(int i=1;i<=n;++i) ans+=(long long)v[i]*(r[i]-i)*(i-l[i]);
    for(int i=1;i<=n;s[++t]=i++)
    for(;t&&v[i]<v[s[t]];--t) r[s[t]]=i;
    for(;t;--t) r[s[t]]=n+1;
    for(int i=n;i;s[++t]=i--)
    for(;t&&v[i]<=v[s[t]];--t) l[s[t]]=i;
    for(;t;--t) l[s[t]]=0;
    for(int i=1;i<=n;++i) ans-=(long long)v[i]*(r[i]-i)*(i-l[i]);
    printf("%lld\n",ans);
}

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') { // 提取关键特征点 const forehead = (facePoints[19].y + facePoints[24].y) / 2; // 额头平均y坐标 const eyeLine = (facePoints[36].y + facePoints[45].y) / 2; // 眼线平均y坐标 const jawLine = (facePoints[1].y + facePoints[17].y + facePoints[8].y) / 3; // 下颌平均y坐标 // 计算头部俯仰角(基于三点连线斜率) const upperDist = Math.abs(eyeLine - forehead); // 额头到眼线的垂直距离 const lowerDist = Math.abs(jawLine - eyeLine); // 眼线到下颌的垂直距离 const pitchRatio = upperDist / lowerDist; // 俯仰比(低头时upperDist增大,pitchRatio上升) // 初始化基准(取前5帧的pitchRatio均值作为静止基准) if (!self.nodBaseRatio) { self.nodRatioHistory = self.nodRatioHistory || []; self.nodRatioHistory.push(pitchRatio); if (self.nodRatioHistory.length >= 5) { self.nodBaseRatio = self.nodRatioHistory.reduce((a, b) => a + b, 0) / 5; self.nodRatioHistory = []; // 重置历史,开始监测动作 self.currentPrompt = '请缓慢点头(上下移动)'; } return; } // 动态阈值(基于基准值的比例,而非固定数值) const nodUpThreshold = self.nodBaseRatio * 0.85; // 抬头时pitchRatio降低(低于基准15%) const nodDownThreshold = self.nodBaseRatio * 1.15; // 低头时pitchRatio升高(高于基准15%) // 动作趋势分析(需完成“低头→抬头”完整周期) self.nodRatioHistory = self.nodRatioHistory || []; self.nodRatioHistory.push({ ratio: pitchRatio, time: Date.now() }); if (self.nodRatioHistory.length > 8) self.nodRatioHistory.shift(); // 保留最近8帧(约640ms) // 判断是否出现“先低头(超过down阈值)再抬头(低于up阈值)”的完整趋势 const hasDown = self.nodRatioHistory.some(r => r.ratio > nodDownThreshold); const hasUp = self.nodRatioHistory.some(r => r.ratio < nodUpThreshold); // 趋势有效性验证:最高点出现在最低点之后(先低头后抬头) const downPoint = self.nodRatioHistory.find(r => r.ratio > nodDownThreshold); const upPoint = self.nodRatioHistory.findLast(r => r.ratio < nodUpThreshold); const trendValid = downPoint && upPoint && downPoint.time < upPoint.time; // 时间有效性验证(动作持续0.3-1.5秒) const actionDuration = self.nodRatioHistory.length > 1 ? self.nodRatioHistory[self.nodRatioHistory.length - 1].time - self.nodRatioHistory[0].time : 0; const timeValid = actionDuration > 300 && actionDuration < 1500; if (hasDown && hasUp && trendValid && timeValid) { self.currentPrompt = '点头完成!'; self.promptStatus = 'success'; self.goToNextStep(); // 重置状态,避免重复触发 self.nodBaseRatio = null; self.nodRatioHistory = []; } 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') { // 1. 提取上下眼睑特征点(68点模型) const leftUpperEye = [37, 38].map(idx => facePoints[idx]); const leftLowerEye = [40, 41].map(idx => facePoints[idx]); const rightUpperEye = [43, 44].map(idx => facePoints[idx]); const rightLowerEye = [46, 47].map(idx => facePoints[idx]); // 2. 计算左右眼上下眼睑的平均距离 const calculateEyeOpening = (upperPoints, lowerPoints) => { // 计算上下眼睑之间的平均垂直距离 const dist1 = Math.hypot(upperPoints[0].x - lowerPoints[0].x, upperPoints[0].y - lowerPoints[0].y); const dist2 = Math.hypot(upperPoints[1].x - lowerPoints[1].x, upperPoints[1].y - lowerPoints[1].y); return (dist1 + dist2) / 2; }; const leftOpening = calculateEyeOpening(leftUpperEye, leftLowerEye); const rightOpening = calculateEyeOpening(rightUpperEye, rightLowerEye); const currentOpening = (leftOpening + rightOpening) / 2; // 3. 初始化睁眼基准值(前5帧取平均) self.eyeOpenBase = self.eyeOpenBase || null; self.eyeCalibrationFrames = self.eyeCalibrationFrames || []; if (self.eyeOpenBase === null) { self.eyeCalibrationFrames.push(currentOpening); if (self.eyeCalibrationFrames.length >= 5) { // 计算基准值(去掉极值,取中间3帧平均) const sorted = [...self.eyeCalibrationFrames].sort((a, b) => a - b).slice(1, -1); self.eyeOpenBase = sorted.reduce((a, b) => a + b, 0) / sorted.length; self.currentPrompt = '请缓慢眨眼'; console.log(`眨眼基准值校准完成: ${self.eyeOpenBase.toFixed(2)}px`); } else { self.currentPrompt = '请保持正视前方(正在校准)'; return; } } // 4. 记录历史数据(保留最近10帧) self.eyeOpeningHistory = self.eyeOpeningHistory || []; self.eyeOpeningHistory.push({ opening: currentOpening, time: Date.now() }); if (self.eyeOpeningHistory.length > 10) self.eyeOpeningHistory.shift(); // 5. 计算变化率(当前帧与5帧前的比值) const getChangeRate = () => { if (self.eyeOpeningHistory.length < 6) return 1; const prev = self.eyeOpeningHistory[self.eyeOpeningHistory.length - 6].opening; return currentOpening / prev; }; // 6. 眨眼判定条件 // A. 眼睛闭合程度(当前距离小于基准的50%) const isClosed = currentOpening < self.eyeOpenBase * 0.5; // B. 快速闭合(变化率小于0.7,即闭合超过30%) const changeRate = getChangeRate(); const isFastClosing = changeRate < 0.7; // C. 完整眨眼周期(先闭合后睁开) const isBlinkCycle = () => { if (self.eyeOpeningHistory.length < 7) return false; // 找到最近的闭合点 const closedPoint = self.eyeOpeningHistory.slice(-7).find(h => h.opening < self.eyeOpenBase * 0.6); if (!closedPoint) return false; // 闭合点之后有明显的睁开动作 const closedIndex = self.eyeOpeningHistory.indexOf(closedPoint); const subsequentPoints = self.eyeOpeningHistory.slice(closedIndex); return subsequentPoints.some(h => h.opening > self.eyeOpenBase * 0.85); }; // 7. 综合判定(满足任一条件即可) const isBlink = isClosed || (isFastClosing && isBlinkCycle()); if (isBlink) { self.currentPrompt = '眨眼完成!'; self.promptStatus = 'success'; self.goToNextStep(); // 重置状态 self.eyeOpenBase = null; self.eyeOpeningHistory = []; } else { self.currentPrompt = `请眨眼(基准: ${self.eyeOpenBase.toFixed(2)}px, 当前: ${currentOpening.toFixed(2)}px)`; self.promptStatus = 'warning'; } // 调试信息 console.log(`眼睛开度: ${currentOpening.toFixed(2)}px, 基准: ${self.eyeOpenBase.toFixed(2)}px, 变化率: ${changeRate.toFixed(2)}`); } // 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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值