蚂蚁感冒 (数学 C++)

1211. 蚂蚁感冒 - AcWing题库

首先想到的就是用结构体来记录蚂蚁的状态,根据绝对位置来排序蚂蚁,遍历所有蚂蚁,如果相向则接着去判断他们是否感冒,如果感冒则都变成感冒状态,然后改变两只蚂蚁的方向

代码如下:

复制代码
#include <iostream>
#include <vector>
#include <cmath> // 用于abs函数
#include <algorithm>

using namespace std;

struct Ant {
    int position; // 蚂蚁的位置
    bool hasCold; // 蚂蚁是否感冒
};

bool compare(const Ant &a, const Ant &b) {
    return abs(a.position) < abs(b.position);
}

int main() {
    int n;
    cin >> n;
    vector<Ant> ants(n);

    // 初始化蚂蚁的位置和感冒状态
    for (int i = 0; i < n; i++) {
        cin >> ants[i].position;
        ants[i].hasCold = (i == 0); // 第一只蚂蚁感冒了
    }
    
    sort(ants.begin(), ants.end(), compare);

    // 遍历蚂蚁,使用双指针法
    for (int i = 0; i < n - 1; ) {
        // 检查当前蚂蚁和下一只蚂蚁是否相向而行
        if (ants[i].position > 0 && ants[i + 1].position < 0) { // 如果符号相反,则相向而行
            // 如果至少有一只蚂蚁感冒,则两只都感冒
            if (ants[i].hasCold || ants[i + 1].hasCold) {
                ants[i].hasCold = true;
                ants[i + 1].hasCold = true;
            }
            // 改变两只蚂蚁的方向
            ants[i].position = -ants[i].position;
            ants[i + 1].position = -ants[i + 1].position;
            
            
            
            if (i >= 2 ) i -= 2;
        }
    
        i++; // 移动到下一只蚂蚁
    }

    // 计算感冒蚂蚁的数量
    int coldCount = 0;
    for (int i = 0; i < n; i++) {
        if (ants[i].hasCold) {
            coldCount++;
        }
    }

    cout << coldCount << endl;

    return 0;
}

代码提交状态: Wrong Answer

代码运行状态: 错误数据如下所示 ×

输入:

5

-6 7 1 5 -8

输出

复制代码
3

标准答案

4

转换思路

可以将蚂蚁碰面后调头视为穿过

以第一只蚂蚁向右举例,在它右边的蚂蚁如果向左则会被感染,那么记录右边中向左蚂蚁的数量

对于左边的蚂蚁而言,如果有右边中有感染的蚂蚁方向向左,那么向右的蚂蚁就会感染,否则就不用担心

if (第一只蚂蚁向右,并且右边向左蚂蚁的数量为0)则感冒的蚂蚁数量为1

否则 感冒的蚂蚁数量为 left + right + 1

初始蚂蚁向左同理可推,

if (第一只蚂蚁向右,并且左边向右蚂蚁的数量为0)则感冒的蚂蚁数量为1

否则 感冒的蚂蚁数量为 left + right + 1

代码如下:

复制代码
#include <iostream>

using namespace std;

const int N = 55;

int s[N];

int main() {
    int n;
    cin >> n;
    for (int i = 0;i < n;i++) {
        cin >> s[i];
    }
    int left = 0,right = 0;
    for (int i = 1;i < n;i++) {
        if (abs(s[i]) < abs(s[0]) && s[i] > 0) right++;
        else if (abs(s[i]) > abs(s[0]) && s[i] < 0) left++;
    }
    
    if ((s[0] > 0 && left == 0) || (s[0] < 0 && right == 0)) cout << 1 << endl;
    else cout << left + right + 1 << endl;
    
    return 0;
   
}
相关推荐
AI 小老六7 分钟前
Agent 记忆系统难在取舍
人工智能·算法·架构·agent·memory·harness
大熊背9 分钟前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(一)
数码相机·算法·白平衡·色度色域
不会就选b10 分钟前
算法日常・每日刷题--<贪心>13
算法
带多刺的玫瑰23 分钟前
Leecode#35刷题之搜索插入位置
java·python·算法
我不会起名字3221 小时前
万字总结Golang入门项目
数据结构·经验分享·算法·golang·项目实战·复盘
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 14. 最长公共前缀 | C++ 纵向扫描法与防越界细节
c++·算法·leetcode
Niuguangshuo9 小时前
论文解读:CTC,端到端序列识别的开山之作
算法·语音识别
讳疾忌医丶9 小时前
深度拆解 RocksDB 内核:基于 C++17 的 FIFO 调度状态机与温度阶梯自愈设计
java·c++·算法·架构
高亦真10 小时前
今天是学习嵌入式的第37天
linux·学习·算法
罗西的思考11 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 --- (2)--- 训练
人工智能·算法·机器学习