首页 > 专题系列 > Java解POJ > POJ 1852 Ants [解题报告] Java
2013
11-10

POJ 1852 Ants [解题报告] Java

Ants

问题描述 :

An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.

输入:

The first line of input contains one integer giving the number of cases that follow. The data for each case start with two integer numbers: the length of the pole (in cm) and n, the number of ants residing on the pole. These two numbers are followed by n integers giving the position of each ant on the pole as the distance measured from the left end of the pole, in no particular order. All input integers are not bigger than 1000000 and they are separated by whitespace.

输出:

For each case of input, output two numbers separated by a single space. The first number is the earliest possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) and the second number is the latest possible such time.

样例输入:

2
10 3
2 6 7
214 7
11 12 7 13 176 23 191

样例输出:

4 8
38 207

解题代码:

//* @author: ccQ.SuperSupper
import java.io.*;
import java.util.*;
public class Main {

	/**
	 * @param args
	 */
	static int max(int a,int b)
	{
		if(a>b) return a;
		return b;
	}
	static int min(int a,int b)
	{
		if(a>b) return b;
		return a;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int t,n,m,ans1,ans2,i,k;
		
		Scanner cin = new Scanner(System.in);
		
		t = cin.nextInt();
		while(t>0)
		{
			--t;
			
			n = cin.nextInt();
			m = cin.nextInt();
			
			ans1 = 0;ans2 = 0;
			
			for(i=0;i< m;++i)
			{
				k = cin.nextInt();
				ans1 = max(ans1,min(k,n-k));
				ans2 = max(ans2,max(k,n-k));
			}
			System.out.println(ans1+" "+ans2);
		}

	}

}

  1. 思路二可以用一个长度为k的队列来实现,入队后判断下队尾元素的next指针是否为空,若为空,则出队指针即为所求。

  2. 网站做得很好看,内容也多,全。前段时间在博客园里看到有人说:网页的好坏看字体。觉得微软雅黑的字体很好看,然后现在这个网站也用的这个字体!nice!

  3. Excellent Web-site! I required to ask if I might webpages and use a component of the net web website and use a number of factors for just about any faculty process. Please notify me through email regardless of whether that would be excellent. Many thanks

  4. 第一题是不是可以这样想,生了n孩子的家庭等价于n个家庭各生了一个1个孩子,这样最后男女的比例还是1:1