Java實現算法競賽入門經典例題-螞蟻

問題描述
一根長度爲L釐米的木棍上有n只螞蟻,每隻螞蟻要麼朝左爬,要麼朝右爬,速度爲1釐米/秒。
當兩隻螞蟻相撞時,二者同時掉頭(掉頭時間忽略不計)。
給出每隻螞蟻的初始位置和朝向,計算T秒之後每隻螞蟻的位置。

輸入格式
輸入的第一行爲數據組數。每組數據的第一行爲3個正整數L, T, n(0≤n≤10 000);以下n行每行描述一隻螞蟻的初始位置,
其中,整數x爲螞蟻距離木棍左端的距離(單位:釐米),字母表示初始朝向(L表示朝左,R表示朝右)。

輸出格式
對於每組數據,輸出n行,按輸入順序輸出每隻螞蟻的位置和朝向(Turning表示正在碰撞)。
在第T秒之前已經掉下木棍的螞蟻(正好爬到木棍邊緣的不算)輸出Fell off。

樣例輸入1
2
10 1 4
1 R
5 R
3 L
10 R
10 2 3
4 R
5 L
8 R

樣例輸出1
Case #1:
2 Turning
6 R
2 Turning
Fell off

Case #2:
3 L
6 R
10 R

PS:
當兩隻螞蟻相撞我可以當作兩隻螞蟻穿過去
雖然我再不停的轉頭,但是我的相對位置一直沒變
我最開始掉下去得永遠是最靠邊得兩隻

package 第七次模擬;

import java.util.Arrays;
import java.util.Scanner;

public class Demo2螞蟻 {
	public static class Node implements Comparable<Node> {
		int id;// 輸入順序
		int location;// -1,0,1
		int p;// 位置

		@Override
		public int compareTo(Node o) {
			// TODO 自動生成的方法存根
			if (this.p > o.p) {
				return 1;
			} else if (this.p < o.p) {
				return -1;
			}
			return 0;
		}
	}

	public static Node[] start;
	public static Node[] end;
	public static int[] order;
	public static String[] loca = { "L", "Turning", "R" };;

	public static void main(String[] args) {
		int num=1;
		Scanner sc = new Scanner(System.in);
		int count = sc.nextInt();
		while (count-- > 0) {

			int l = sc.nextInt();
			int t = sc.nextInt();
			int n = sc.nextInt();
			start = new Node[n];
			end = new Node[n];
			order = new int[n];
			for (int i = 0; i < n; i++) {
				start[i] = new Node();
				start[i].p = sc.nextInt();
				String c = sc.next();
				if (c.equals("L"))
					start[i].location = -1;
				else
					start[i].location = 1;
				start[i].id = i;
				end[i] = new Node();
				end[i].id = 0;
				end[i].p = start[i].p + t * start[i].location;
				end[i].location = start[i].location;

			}
			Arrays.sort(start);
			Arrays.sort(end);
			for (int j = 0; j < n; j++) {
				order[start[j].id] = j;
			}
			for (int j = 0; j < n - 1; j++) {
				if (end[j].p == end[j + 1].p) {
					end[j].location = 0;
					end[j + 1].location = 0;
				}
			}
			
			System.out.println("Case #"+ num++ +":");
			for (int i = 0; i < n; i++) {
				int temp = order[i];
				if (end[temp].p > l || end[temp].p < 0) {
					System.out.println("Fell off\n");
				} else {
					System.out.println(end[temp].p + " " + loca[end[temp].location + 1]);
				}
			}
		}
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章