Untitled

 avatar
unknown
plain_text
2 years ago
1.6 kB
5
Indexable
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		for (int t = 1; t <= 10; t++) {
			int N = sc.nextInt();
			int start = sc.nextInt() - 1;
			Queue inQueue = new Queue(N);

			int[][] preMatrix = new int[N][N];

			for (int i = 0; i < N; i += 2) {
				int s = sc.nextInt();
				int e = sc.nextInt();
				inQueue.push(s);
				inQueue.push(e);
				preMatrix[s][e] = 1;
			}

			Queue queue = new Queue(1000);
			boolean visited[] = new boolean[N];

			queue.push(inQueue.valueOf(start));
			int max = 0;
			while (!queue.empty()) {
				max = 0;
				for (int i = 0; i < queue.length(); i++) {
					int x = queue.pop();
					if (x > max ) {
						max = x;
					}
					;
					visited[x] = true;
					for (int j = 0; j < N; j++) {
						if (preMatrix[x][j] == 1 && !visited[j]) {
							queue.push(j);
						}
					}
				}
			}

			System.out.println(max);

		}
		sc.close();

	}

}

class Queue {
	private int front, rear, capacity;
	private int queue[];

	Queue(int c) {
		front = rear = 0;
		capacity = c;
		queue = new int[capacity];
	};

	void push(int data) {
		queue[rear] = data;
		rear++;
	};

	int pop() {
		int res = queue[front];
		for(int i=0; i<rear-1;i++) {
			queue[i] = queue[i+1];
		}
		rear--;
		return res;
	};

	void reset() {
		front = rear = 0;
	};

	boolean empty() {
		return front == rear;
	};

	int valueOf(int index) {
		return queue[index];
	};

	int length() {
		return rear - front;
	};
}
Editor is loading...