Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.*;
- /**
- * Created by camp on 11/26/2014.
- */
- public class TaskB {
- BufferedReader reader;
- StringTokenizer tokenizer;
- PrintWriter writer;
- public String nextToken() throws IOException {
- while (tokenizer == null || !tokenizer.hasMoreTokens()) {
- tokenizer = new StringTokenizer(reader.readLine());
- }
- return tokenizer.nextToken();
- }
- public int nextInt() throws IOException {
- return Integer.parseInt(nextToken());
- }
- public double nextDouble() throws IOException {
- return Double.parseDouble(nextToken());
- }
- public long nextLong() throws IOException {
- return Long.parseLong(nextToken());
- }
- public static void main(String[] args) throws IOException {
- new TaskB().run();
- }
- public void solve() throws IOException {
- int n = nextInt();
- TreeMap<String, HashSet<String>> map = new TreeMap<String, HashSet<String>>();
- for (int i = 0; i < n; i++) {
- String s1 = nextToken();
- StringBuilder s2 = new StringBuilder();
- while (tokenizer.hasMoreTokens()) {
- s2.append(nextToken()).append(" ");
- }
- s2.deleteCharAt(s2.length() - 1);
- if (map.containsKey(s1)) {
- map.get(s1).add(s2.toString());
- } else {
- map.put(s1, new HashSet<String>());
- map.get(s1).add(s2.toString());
- }
- }
- boolean[] finished = new boolean[120];
- StringBuilder builder = new StringBuilder();
- int s = map.size();
- String lastS1 = "A";
- for (int i = 0; i < s; i++) {
- Map.Entry<String, HashSet<String>> e = map.firstEntry();
- for (char c : lastS1.toCharArray()) {
- if (!e.getKey().contains(String.valueOf(c))) {
- finished[c] = true;
- }
- }
- for (char c : e.getKey().toCharArray()) {
- if (finished[c]) {
- writer.println("Impossible");
- return;
- }
- }
- // if (e.getKey().equals(lastS1) || (Character.valueOf(e.getKey().charAt(0)).compareTo(lastS1.charAt(lastS1.length() - 1)) >= 0)) {
- for (String s2 : e.getValue()) {
- builder.append(e.getKey()).append(" ").append(s2).append("\n");
- }
- lastS1 = e.getKey();
- // } else {
- // writer.println("Impossible");
- // return;
- // }
- map.remove(e.getKey(), e.getValue());
- }
- writer.println(builder.toString());
- }
- public void run() {
- try {
- reader = new BufferedReader(new FileReader("b.in"));
- writer = new PrintWriter("b.out");
- solve();
- writer.close();
- } catch (IOException e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement