Pagini recente » Cod sursa (job #1174701) | Cod sursa (job #1455948) | Cod sursa (job #2502198) | Cod sursa (job #1261085) | Cod sursa (job #2675792)
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static ArrayList<ArrayList<Integer>> adjacent = new ArrayList<>();
public static ArrayList<ArrayList<Integer>> C = new ArrayList<>();
public static ArrayList<ArrayList<Integer>> flow = new ArrayList<>();
public static ArrayList<Boolean> seen = new ArrayList<>();
public static ArrayList<Integer> a = new ArrayList<>();
public static ArrayList<Integer> last = new ArrayList<>();
public static int start,finish;
public static int m = 1005;
public static int result = 0;
public static void initAlgo() {
for(int i = 0; i < m; ++i) {
C.add(new ArrayList<>());
flow.add(new ArrayList<>());
adjacent.add(new ArrayList<>());
seen.add(false);
a.add(0);
last.add(0);
for(int j = 0; j < m; ++j) {
flow.get(i).add(0);
C.get(i).add(0);
}
}
}
public static void getMaxFlow() {
boolean add_flow = true;
while(add_flow) {
add_flow = false;
for(int i = 0;i < m;++i) {
seen.set(i,false);
a.set(i,0);
}
var q = new ArrayList<Integer>();
int b=-1;
seen.set(start,true); a.set(start,1000000);
q.add(start);
while(b<q.size()-1 && !seen.get(finish)) {
b += 1;
int x = q.get(b);
for(Integer y : adjacent.get(x)) if(!seen.get(y) && C.get(x).get(y)-flow.get(x).get(y) > 0) {
last.set(y,x);
a.set(y,Math.min(a.get(x),C.get(x).get(y)-flow.get(x).get(y)));
q.add(y);
seen.set(y,true);
}
}
if(seen.get(finish)) {
result += a.get(finish);
add_flow = true;
int y = finish, x = last.get(finish);
while(y != start) {
int i = flow.get(x).get(y);
flow.get(x).set(y,i+a.get(finish));
i = flow.get(y).get(x);
flow.get(y).set(x,i-a.get(finish));
y = x;
x = last.get(x);
}
}
}
}
public static void readGraph() throws IOException {
String infile = "maxflow.in";
Scanner scanner = new Scanner(new FileInputStream(infile));
finish = scanner.nextInt();
start = 1;
m = finish+1;
int mu = scanner.nextInt();
int x,y,c;
for(int i=0;i<mu;++i) {
x = scanner.nextInt();
y = scanner.nextInt();
c = scanner.nextInt();
adjacent.get(x).add(y);
adjacent.get(y).add(x);
C.get(x).set(y,c);
}
}
public static void solution2() throws IOException{
String outfile = "maxflow.out";
initAlgo();
readGraph();
getMaxFlow();
PrintStream printer = new PrintStream(outfile);
printer.println(result);
}
public static void main(String[] args) throws IOException{
solution2();
}
}