summaryrefslogtreecommitdiffstats
path: root/Algorithms/Part-II/3-BaseballElimination/BaseballElimination.java
blob: 2c65a4a7be2302606e259167b2b4527d70480c75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/* vim: set expandtab tabstop=4 shiftwidth=4 : */

import java.util.HashMap;

public class BaseballElimination
{
    private static final boolean DEBUG = false;

    private int n;
    private String[] names;
    private int[] wins;
    private int[] losses;
    private int[] remains;
    private int[][] games;
    private HashMap<String, Integer> nameToI;
    private boolean[] eliminated;
    private HashMap<Integer, Stack<String>> eliminatedBy;

    public BaseballElimination(String filename)
    {
        In in = new In(filename);

        n = in.readInt();

        names = new String[n];
        wins = new int[n];
        losses = new int[n];
        remains = new int[n];
        games = new int[n][n];
        nameToI = new HashMap<String, Integer>();
        eliminated = new boolean[n];
        eliminatedBy = new HashMap<Integer, Stack<String>>();

        for (int i = 0; i < n; i++) {
            names[i] = in.readString();
            wins[i] = in.readInt();
            losses[i] = in.readInt();
            remains[i] = in.readInt();
            for (int j = 0; j < n; j++) {
                games[i][j] = in.readInt();
            }
            nameToI.put(names[i], i);
        }

        trivialEliminations();

        for (int i = 0; i < n; i++) {
            // if (!eliminated[i] && shouldBeEliminated(i)) {
            if (!eliminated[i]) {
                maxFlowComputation(i);
            }
        }
    }

    private void addEliminatedBy(int who, int by)
    {
        Stack<String> s = eliminatedBy.get(who);
        if (s == null) {
            s = new Stack<String>();
            s.push(names[by]);
            eliminatedBy.put(who, s);
        } else {
            s.push(names[by]);
        }
    }

    private void trivialEliminations()
    {
        // even if the team wins all its remaining games
        // it won't catch up with the best teams
        for (int i = 0; i < n; i++) {
            int w = wins[i] + remains[i];
            for (int j = 0; j < n; j++) {
                // (i == j) is safe
                if (w < wins[j]) {
                    eliminated[i] = true;
                    addEliminatedBy(i, j);
                }
            }
        }
    }

    private boolean shouldBeEliminated(int t)
    {
        // even if the team wins all its remaining games
        // it won't catch up with the min of the others wins
        int w = wins[t] + remains[t];
        int ws = 0;
        for (int i = 0; i < n; i++) {
            if (i == t) continue;
            ws += wins[i];
            for (int j = i; j < n; j++) {
                if (j == t) continue;
                ws += games[i][j];
            }
        }
        if (w < Math.ceil(ws / (float) (n-1))) {
            return true;
        }
        return false;
    }

    private int countGamesWithout(int t)
    {
        int c = 0;
        for (int i = 0; i < n; i++) {
            if (i == t) continue;
            for (int j = i; j < n; j++) {
                if (j == t) continue;
                if (games[i][j] > 0) c++;
            }
        }

        return c;
    }

    private void maxFlowComputation(int t)
    {
        int g = countGamesWithout(t);
        // s + t + games + teams
        int vertices = 2 + g + n;

        FlowNetwork flowNetwork = new FlowNetwork(vertices);

        int S = vertices - 2;
        int T = vertices - 1;
        int idx = n;
        int b = wins[t] + remains[t];
        for (int i = 0; i < n; i++) {
            if (i == t) continue;
            // team -> T
            FlowEdge e = new FlowEdge(i, T, (b - wins[i]));
            flowNetwork.addEdge(e);
            for (int j = i; j < n; j++) {
                if (j == t) continue;
                if (games[i][j] > 0) {
                    // S -> game
                    e = new FlowEdge(S, idx, games[i][j]);
                    flowNetwork.addEdge(e);
                    // game -> team i
                    e = (new FlowEdge(idx, i, Double.POSITIVE_INFINITY));
                    flowNetwork.addEdge(e);
                    // game -> team j
                    e = (new FlowEdge(idx, j, Double.POSITIVE_INFINITY));
                    flowNetwork.addEdge(e);
                    idx++;
                }
            }
        }

        if (DEBUG) {
            System.out.println(names[t]+" should be out…");
            System.out.println(flowNetwork.toString());
        }

        FordFulkerson maxFlow = new FordFulkerson(flowNetwork, S, T);

        if (DEBUG) {
            System.out.println(flowNetwork.toString());
            System.out.printf("Team: %s got :%g \n", names[t], maxFlow.value());
        }

        boolean out = false;
        for (FlowEdge e : flowNetwork.adj(S)) {
            if (DEBUG) System.out.println(e);
            if (e.flow() != e.capacity()) {
                out = true;
                break;
            }
        }

        if (out) {
            eliminated[t] = true;
            for (int i = 0; i < n; i++) {
                if (maxFlow.inCut(i) && !eliminated[i]) {
                    addEliminatedBy(t, i);
                }
            }
        }
    }

    private int teamI(String team)
    {
        Object i = nameToI.get(team);
        if (i == null)
            throw new IllegalArgumentException(team);

        return (int) i;
    }

    public int numberOfTeams()
    {
        return n;
    }

    public Iterable<String> teams()
    {
        return nameToI.keySet();
    }

    public int wins(String team)
    {
        return wins[teamI(team)];
    }

    public int losses(String team)
    {
        return losses[teamI(team)];
    }

    public int remaining(String team)
    {
        return remains[teamI(team)];
    }

    public int against(String team1, String team2)
    {
        return games[teamI(team1)][teamI(team2)];
    }

    public boolean isEliminated(String team)
    {
        return eliminated[teamI(team)];
    }

    public Iterable<String> certificateOfElimination(String team)
    {
        int t = teamI(team);

        if (!eliminated[t])
            return null;
        else {
            return eliminatedBy.get(t);
        }
    }

    public static void main(String[] args) {
        BaseballElimination division = new BaseballElimination(args[0]);
        for (String team : division.teams()) {
            if (division.isEliminated(team)) {
                StdOut.print(team + " is eliminated by the subset R = { ");
                for (String t : division.certificateOfElimination(team))
                    StdOut.print(t + " ");
                StdOut.println("}");
            }
            else {
                StdOut.println(team + " is not eliminated");
            }
        }
    }
}