Advertisement
Bladtman

Congress

Mar 1st, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. public class Congress {
  2.     int conSeats;
  3.     MaxPQ<State> queue;
  4.  
  5.     public Congress(){
  6.  
  7.     }
  8.  
  9.     public static void main (String args[]){
  10.         Congress c = new Congress();       
  11.         c.readFromFile (args[0]);
  12.         c.apportion();
  13.     }
  14.    
  15.     /*
  16.      * A state has a name, population and is initialized with one seat.
  17.      */
  18.     private class State implements Comparable<State> {
  19.         private String name;
  20.         private int pop;
  21.         private int seats=0;
  22.         private int prior;
  23.  
  24.         public State (String n, int p) {
  25.             this.name = n;
  26.             this.pop = p;
  27.             addSeat();
  28.         }
  29.        
  30.         public void addSeat () {
  31.             this.prior = (int) ((double) pop/Math.sqrt(++seats*(seats+1)));
  32.         }
  33.  
  34.         public String getName() {
  35.             return this.name;
  36.         }
  37.  
  38.         public int getSeats() {
  39.             return seats;
  40.         }
  41.  
  42.         public int getPrior() {
  43.             return this.prior;
  44.         }
  45.  
  46.         public int compareTo(State o){
  47.             return this.prior - o.getPrior();
  48.         }
  49.     }
  50.  
  51.     public void readFromFile(String f) {
  52.         In read = new In(f);
  53.         int sz = Integer.parseInt(read.readLine());
  54.         queue = new MaxPQ<State> (sz);
  55.         conSeats = Integer.parseInt(read.readLine());
  56.  
  57.         for (int i=0; i<sz; i++) {
  58.             String s = read.readLine();
  59.             int p = Integer.parseInt(read.readLine());
  60.             queue.insert(new State(s, p));
  61.         }
  62.     }
  63.  
  64.     public void apportion() {
  65.         int assigns = conSeats - queue.size();
  66.         for (int i=0; i<assigns; i++) {
  67.             State s = queue.eatMax();
  68.             s.addSeat();
  69.             queue.insert(s);
  70.         }
  71.        
  72.         State[] ss = (State[])queue.getList();
  73.         for (int i=1; i<ss.length; i++) {
  74.             System.out.println(ss[i].getName() +"\n" + ss[i].getSeats());
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement