蚂蚁感冒 (数学 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;
   
}
相关推荐
轻抚酸~3 小时前
KNN(K近邻算法)-python实现
python·算法·近邻算法
Yue丶越5 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
小白程序员成长日记6 小时前
2025.11.24 力扣每日一题
算法·leetcode·职场和发展
有一个好名字6 小时前
LeetCode跳跃游戏:思路与题解全解析
算法·leetcode·游戏
AndrewHZ7 小时前
【图像处理基石】如何在图像中提取出基本形状,比如圆形,椭圆,方形等等?
图像处理·python·算法·计算机视觉·cv·形状提取
蓝牙先生7 小时前
简易TCP C/S通信
c语言·tcp/ip·算法
稚辉君.MCA_P8_Java10 小时前
Gemini永久会员 Java中的四边形不等式优化
java·后端·算法
稚辉君.MCA_P8_Java10 小时前
通义 插入排序(Insertion Sort)
数据结构·后端·算法·架构·排序算法
无限进步_11 小时前
C语言动态内存的二维抽象:用malloc实现灵活的多维数组
c语言·开发语言·数据结构·git·算法·github·visual studio
Swift社区11 小时前
LeetCode 432 - 全 O(1) 的数据结构
数据结构·算法·leetcode