蓝桥杯 蚂蚁感冒(Java)

解题思路:根据第一个感冒蚂蚁的行驶方向,分为两种情况(向左,右),如果他朝右走,则在他右边有朝左走的蚂蚁必然都会被传染(如果右边没有向左的蚂蚁,则不会有蚂蚁被传染,直接输出结果),此时在它右边的不必再统计,只需再统计它左边朝右走的蚂蚁,他们也必定会被传染。(如果第一只蚂蚁朝左走,情况类似。)
解题难点:如果单纯的利用画图演示想要理解一个完整的感冒传播过程,还是比较难以理解,我也是根据观看他人的思路总结才能写出这个java代码。感谢大佬:https://blog.csdn.net/xihahua/article/details/89692958

import java.util.Scanner; 

public class Main {
	public static void main(String[] args) {
		Scanner scanf = new Scanner(System.in);
		int n = scanf.nextInt();               //记录蚂蚁总数
		int num = 1;                           //统计感冒蚂蚁的总数
		int temp = 0;                          //统计局部感冒蚂蚁的总数
		int ants[] = new int[200];
		
		for(int i = 0;i < n;i++)               //分别输入蚂蚁所在的位置和方向
			ants[i] = scanf.nextInt();
		if(ants[0] > 0) {                      //如果第一只感冒蚂蚁向右走
			for(int i = 1;i < n;i++) {         
				if(ants[i] < 0 && -ants[i] > ants[0])
					temp++;
			}
			num += temp;
			if(temp == 0)                      //如果右边没有向左走的情况
				System.out.print(1);
			else {
				temp = 0;
				for(int i = 1;i < n;i++) {
					if(ants[i] > 0 && ants[i] < ants[0])
						temp++;
				}
				num += temp;
			}
		}
		else {                                 //第一只蚂蚁向左走的情况
			temp = 0;
			for(int i = 1;i < n;i++) {
				if(ants[i] > 0 && ants[i] < -ants[0])
					temp++;
			}
			num += temp;
			if(temp == 0)
				System.out.print(1);
			else {
				temp = 0;
				for(int i = 1;i < n;i++) {
					if(ants[i] < 0 && ants[i] < ants[0])
						temp++;
				}
				num += temp;
			}
		}
		System.out.print(num);
	}
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值