蚂蚁感冒 (数学 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;
   
}
相关推荐
茉莉玫瑰花茶11 小时前
算法 --- 字符串
算法
博笙困了11 小时前
AcWing学习——差分
c++·算法
NAGNIP11 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP11 小时前
大模型微调框架之LLaMA Factory
算法
echoarts11 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客11 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕11 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
小刘鸭地下城11 小时前
深入浅出链表:从基础概念到核心操作全面解析
算法
小刘鸭地下城12 小时前
哈希表核心精要:从 O(1) 原理到链式地址与开放寻址
算法
BenChuat12 小时前
Java常见排序算法实现
java·算法·排序算法