ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1167. Bicolored Horses

java AC 1st place
Posted by esbybb 12 Jul 2015 09:59
package timus;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class p1167 {
    static int a[], totals[];
    static int h, s;
    static int min = Integer.MAX_VALUE;
    public static void main(String[] args) throws FileNotFoundException {
        InputStream is = System.in;
//        is = new FileInputStream(new File("A.txt"));
        FastScanner sc = new FastScanner(new InputStreamReader(is));
        h = sc.nextInt();
        s = sc.nextInt();
        int k[] = new int[h];
        for (int i=0; i<h; i++) {
            k[i] = sc.nextInt();
        }
        totals = new int[h+1];
        totals[1] = k[0];
        for (int i=2; i<h+1; i++) {
            totals[i]=totals[i-1]+k[i-1];
        }
        int maxcap = h-s+1;
        int unhappines[][] = new int[h+1][h+1];
        for (int i=1; i<=/*maxcap*/h; i++) {
            int up = Math.min(h, maxcap+i);
            for (int j=i; j<=up; j++) {
                int len = j-i+1;
                int ones = totals[j]-totals[i-1];
                unhappines[i][j] = (len-ones)*ones;
            }
        }
        int a[][] = new int[h+1][s+1];
        for (int i=1; i<=h; i++) {
            Arrays.fill(a[i], Integer.MAX_VALUE);
        }
        int maxes[] = new int[s+1];
        for (int i=1; i<=s; i++) {
            maxes[i] = maxcap+i-1;
        }
        for (int i=1; i<=maxcap; i++) {
            a[i][1] = unhappines[1][i];
        }
        for (int stable=2; stable<=s; stable++) {
            for (int i=stable; i<=maxes[stable]; i++) {
                for (int j=i; j<=maxes[stable]; j++) {
                    int prev = a[i-1][stable-1];
                    a[j][stable] = Math.min(a[j][stable], unhappines[i][j]+prev );
                }
            }
        }
        System.out.println(a[h][s]);
    }

    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }

}