Thinking question: ants catch a cold

Resource Limitation
Time Limitation: 1.0s Memory Limitation: 256.0MB
Problem Description
  There are n ants on the 100 cm long slender straight pole. Some of their heads are facing left and some are facing right.

Each ant can only climb forward along the pole at a speed of 1 cm/sec.

When two ants meet, they will turn around and crawl in opposite directions at the same time.

Among these ants, one ant caught a cold. And when you meet with other ants, you will spread a cold to the ants you encounter.

Please calculate how many ants caught a cold when all the ants climbed away from the pole.
Input format
  input an integer n (1 <n <50) in the first line, which means the total number of ants.

The next line is n integers Xi (-100 <Xi <100) separated by spaces. The absolute value of Xi represents the distance between the ant and the left end of the pole. A positive value indicates that the head is facing right, and a negative value indicates that the head is facing left. There will be no zero value in the data, and no two ants occupying the same position. Among them, the ant represented by the first data has caught a cold.
Output format
  requires the output of 1 integer, which represents the number of ants that caught a cold at the end.
  
Sample input
3
5 -2 8

Sample output
1

Sample input
5
-10 8 -20 12 25

Sample output
3

Idea:
This is a thinking question. Pay attention to the question: When two ants meet, they will turn around and crawl in opposite directions at the same time . It can be changed to: When two ants meet, they will pass through each other and move on. Here It can be considered that the two have exchanged identities , which makes the meaning of the question simple. As long as it is opposite to the infected ant, it will be contagious, so we only need to judge the number of ants that are opposite to the first ant.

Give an example

Ant 1 (—>) Ant 2 (—>) Ant 3 (<—) Infected ant 3 (<—)

If there are 2—>, there must be 2 ants infected

#include<stdio.h>
#include<math.h>
int main()
{
    
    
	int n;
	while(~scanf("%d",&n))
	{
    
    
		int t1;             //代表 首只蚂蚁(感染者) 
		int t2;             //代表 其它的蚂蚁
		int left=0;         //代表 首只感染者 左边向右走 的蚂蚁个数 
		int right=0;        //代表 首只感染者 右边向右走 的蚂蚁个数 
		int sum=0;          //代表 最后被感染的蚂蚁个数 
		scanf("%d",&t1);
		n--;
		while(n--)
		{
    
    
			scanf("%d",&t2);
			if((abs(t1)>abs(t2))&&t2>0)
				left++;
			if(abs(t1)<abs(t2)&&t2<0)
				right++; 
		}
		if((left==0&&t1<0)||(right==0&&t1>0))//首只蚂蚁在最右边且首只蚂蚁向右走||首只蚂蚁在最左边且首只蚂蚁向左走
			sum=0;
		else
			sum=left+right;//只要首只蚂蚁在中间,两边的都会有蚂蚁被感染
		printf("%d\n",sum+1); 
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/Helinshan/article/details/109030482