Competitive Programming: POJ 1125 – Stockbroker Grapevine

 

Description

Stockbrokers are known to overreact to rumors. You have been contracted to develop a method of spreading disinformation amongst the stockbrokers to give your employer the tactical edge in the stock market. For maximum effect, you have to spread the rumors in the fastest possible way.

Unfortunately for you, stockbrokers only trust information coming from their “Trusted sources” This means you have to take into account the structure of their contacts when starting a rumor. It takes a certain amount of time for a specific stockbroker to pass the rumor on to each of his colleagues. Your task will be to write a program that tells you which stockbroker to choose as your starting point for the rumor, as well as the time it will take for the rumor to spread throughout the stockbroker community. This duration is measured as the time needed for the last person to receive the information.

Input

Your program will input data for different sets of stockbrokers. Each set starts with a line with the number of stockbrokers. Following this is a line for each stockbroker which contains the number of people who they have contact with, who these people are, and the time taken for them to pass the message to each person. The format of each stockbroker line is as follows: The line starts with the number of contacts (n), followed by n pairs of integers, one pair for each contact. Each pair lists first a number referring to the contact (e.g. a ‘1’ means person number one in the set), followed by the time in minutes taken to pass a message to that person. There are no special punctuation symbols or spacing rules.

Each person is numbered 1 through to the number of stockbrokers. The time taken to pass the message on will be between 1 and 10 minutes (inclusive), and the number of contacts will range between 0 and one less than the number of stockbrokers. The number of stockbrokers will range from 1 to 100. The input is terminated by a set of stockbrokers containing 0 (zero) people.

Output

For each set of data, your program must output a single line containing the person who results in the fastest message transmission, and how long before the last person will receive any given message after you give it to this person, measured in integer minutes.

It is possible that your program will receive a network of connections that excludes some persons, i.e. some people may be unreachable. If your program detects such a broken network, simply output the message “disjoint”. Note that the time taken to pass the message from person A to person B is not necessarily the same as the time taken to pass it from B to A, if such transmission is possible at all.

Sample Input

3
2 2 4 3 5
2 1 2 3 6
2 1 2 2 2
5
3 4 4 2 8 5 3
1 5 8
4 1 6 4 10 2 7 5 2
0
2 2 5 1 5
0

Sample Output

3 2
3 10

Link to problem

Solution below . . .

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;

/*
 * For all-pairs shortest path problems, Floyd-Warshall is a good 
 * option. Given a directed weighted graph, it outputs a matrix 
 * of all shortest paths between pairs of nodes.
 * 
 * For this problem, each row of the matrix represents a broker.
 * We read each row to find brokers who can get a message to 
 * every other broker, and select the broker with the smallest maximum.
 */

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		AdjMatrixEdgeWeightedDigraph G;

		int brokers = sc.nextInt();

		while (brokers != 0) {
			G = new AdjMatrixEdgeWeightedDigraph(brokers);

			for (int broker = 0; broker < brokers; broker++) {
				int connections = sc.nextInt();

				for (int i = 0; i < connections; i++) {
					int w = sc.nextInt() - 1;
					int weight = sc.nextInt();

					G.addEdge(new DirectedEdge(broker, w, weight));
				}
			}

			FloydWarshall spt = new FloydWarshall(G);

			// find the broker with the shortest max distance
			int min = 9999;
			int minBroker = -1;

			for (int v = 0; v < G.V(); v++) {
				int max = -1;

				for (int w = 0; w < G.V(); w++) {
					if (v != w) {
						if (spt.hasPath(v, w)) {
							max = Math.max(spt.dist(v, w), max);
						} else {
							// this broker can't reach at least one target
							max = 9999;
							break;
						}
					}
				}
				if (max < min) {
					min = max;
					minBroker = v;
				}
			}

			if (minBroker == -1) {
				System.out.println("disjoint");
			} else {
				System.out.println((minBroker + 1) + " " + min);
			}
			brokers = sc.nextInt();
		}
		sc.close();
	}

}

/******************************************************************
 *
 * An edge-weighted digraph, implemented using an adjacency matrix.
 * 
 ******************************************************************/

class AdjMatrixEdgeWeightedDigraph {
	private final int V;
	private int E;
	private DirectedEdge[][] adj;

	public AdjMatrixEdgeWeightedDigraph(int V) {
		this.V = V;
		this.E = 0;
		this.adj = new DirectedEdge[V][V];
	}

	public int V() {
		return V;
	}

	public int E() {
		return E;
	}

	public void addEdge(DirectedEdge e) {
		int v = e.from();
		int w = e.to();
		if (adj[v][w] == null) {
			E++;
			adj[v][w] = e;
		}
	}

	public Iterable<DirectedEdge> adj(int v) {
		return new AdjIterator(v);
	}

	// support iteration over graph vertices
	private class AdjIterator implements Iterator<DirectedEdge>, 
										 Iterable<DirectedEdge> {
		private int v;
		private int w = 0;

		public AdjIterator(int v) {
			this.v = v;
		}

		public Iterator<DirectedEdge> iterator() {
			return this;
		}

		public boolean hasNext() {
			while (w < V) {
				if (adj[v][w] != null)
					return true;
				w++;
			}
			return false;
		}

		public DirectedEdge next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			return adj[v][w++];
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

}

/******************************************************************
 *
 * Immutable weighted directed edge.
 *
 ******************************************************************/

class DirectedEdge {
	private final int v;
	private final int w;
	private final int weight;

	public DirectedEdge(int v, int w, int weight) {
		this.v = v;
		this.w = w;
		this.weight = weight;
	}

	public int from() {
		return v;
	}

	public int to() {
		return w;
	}

	public int weight() {
		return weight;
	}
}

class FloydWarshall {
	// distTo[v][w] = length of shortest v->w path
	private int[][] distTo; 
	// edgeTo[v][w] = last edge on shortest v->w path
	private DirectedEdge[][] edgeTo; 

	private final int MAX = 9999;

	public FloydWarshall(AdjMatrixEdgeWeightedDigraph G) {
		int V = G.V();
		distTo = new int[V][V];
		edgeTo = new DirectedEdge[V][V];

		// initialize distances to max value
		for (int v = 0; v < V; v++) {
			for (int w = 0; w < V; w++) {
				distTo[v][w] = MAX;
			}
		}

		// update distances using digraph
		for (int v = 0; v < G.V(); v++) {
			for (DirectedEdge e : G.adj(v)) {
				distTo[e.from()][e.to()] = e.weight();
				edgeTo[e.from()][e.to()] = e;
			}
		}

		for (int i = 0; i < V; i++) {
			// compute shortest paths using only 
			// 0, 1, ..., i as intermediate vertices
			for (int v = 0; v < V; v++) {
				if (edgeTo[v][i] == null)
					continue; // optimization
				for (int w = 0; w < V; w++) {
					if (distTo[v][w] > distTo[v][i] + distTo[i][w]) {
						distTo[v][w] = distTo[v][i] + distTo[i][w];
						edgeTo[v][w] = edgeTo[i][w];
					}
				}
			}
		}
	}

	public boolean hasPath(int s, int t) {
		return distTo[s][t] < MAX;
	}

	public int dist(int s, int t) {
		return distTo[s][t];
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *