蚂蚁感冒 (数学 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;
   
}
相关推荐
Swift社区7 小时前
LeetCode 465 最优账单平衡
算法·leetcode·职场和发展
聆风吟º7 小时前
【数据结构手札】空间复杂度详解:概念 | 习题
java·数据结构·算法
weixin_445054727 小时前
力扣热题51
c++·python·算法·leetcode
地平线开发者8 小时前
linux 常见稳定性问题分析方法
算法·自动驾驶
s砚山s8 小时前
代码随想录刷题——二叉树篇(九)
算法
地平线开发者8 小时前
大模型常见量化方法简介
算法·自动驾驶
smj2302_7968265211 小时前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
栗少11 小时前
英语自学手册:系统化进阶指南基于《英语自学手册》的方法论与行动路径
人工智能·算法
Xの哲學12 小时前
深入解析 Linux systemd: 现代初始化系统的设计与实现
linux·服务器·网络·算法·边缘计算
sinat_2554878112 小时前
InputStream/OutputStream小讲堂
java·数据结构·算法