解题思路:根据第一个感冒蚂蚁的行驶方向,分为两种情况(向左,右),如果他朝右走,则在他右边有朝左走的蚂蚁必然都会被传染(如果右边没有向左的蚂蚁,则不会有蚂蚁被传染,直接输出结果),此时在它右边的不必再统计,只需再统计它左边朝右走的蚂蚁,他们也必定会被传染。(如果第一只蚂蚁朝左走,情况类似。)
解题难点:如果单纯的利用画图演示想要理解一个完整的感冒传播过程,还是比较难以理解,我也是根据观看他人的思路总结才能写出这个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);
}
}