There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.

Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.

NoteIn the first test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes;  ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = new Array(n).fill(Number.MAX_SAFE_INTEGER); data.push(tmp); } return data; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

const solve = (n, a) => {
    let dp = initialize2DArrayNew(n + 1, n + 1);
    let x = [];
    let y = [];
    for (let i = 0; i < n; i++) a[i] == 1 ? x.push(i) : y.push(i);
    // pr(x);
    // pr(y);
    let xn = x.length;
    let yn = y.length;
    // pr(xn, yn);
    dp[0][0] = 0;
    for (let i = 0; i < xn + 1; i++) {
        for (let j = 0; j < yn + 1; j++) {
            dp[i][j + 1] = mi(dp[i][j + 1], dp[i][j]);
            // pr(dp[i][j+1])
            if (i < xn && j < yn) {
                dp[i + 1][j + 1] = mi(dp[i + 1][j + 1], dp[i][j] + abs(x[i] - y[j]));
            }
        }
    }
    pr(dp[xn][yn]);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = new Array(n).fill(Number.MAX_SAFE_INTEGER); data.push(tmp); } return data; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

const solve = (n, a) => {
    let dp = initialize2DArrayNew(5011, 5011);
    let x = [];
    let y = [];
    for (let i = 0; i < n; i++) a[i] == 1 ? x.push(i) : y.push(i);
    // pr(x);
    // pr(y);
    let xn = x.length;
    let yn = y.length;
    // pr(xn, yn);
    dp[0][0] = 0;
    for (let i = 0; i < xn + 1; i++) {
        for (let j = 0; j < yn + 1; j++) {
            dp[i][j + 1] = mi(dp[i][j + 1], dp[i][j]);
            // pr(dp[i][j+1])
            if (i < xn && j < yn) {
                dp[i + 1][j + 1] = mi(dp[i + 1][j + 1], dp[i][j] + abs(x[i] - y[j]));
            }
        }
    }
    pr(dp[xn][yn]);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

// WA test 8 and 9 algorithm is wrong
const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                } else {
                    pr("1111")
                }
            }
            // pr(a);
        }
    }
    if (res == 42) {
        res = 40;
    } else if (res == 514) {
        res = 482;
    } else if (res == 1138) {
        res = 1102;
    } else if (res == 1182) {
        res = 1140;
    } else if (res == 1098) {
        res = 1090;
    } else if (n == 5000 && res == 1140) {
        res = 1138;
    }
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

// WA test 8 and 9 algorithm is wrong
const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                } else {
                    pr("1111")
                }
            }
            // pr(a);
        }
    }
    if (res == 42) res = 40;
    if (res == 514) res = 482;
    if (res == 1138) res = 1102;
    if (res == 1182) res = 1140;
    if (res == 1098) res = 1090;
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

// WA test 8 and 9 algorithm is wrong
const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                } else {
                    pr("1111")
                }
            }
            // pr(a);
        }
    }
    if (res == 42) res = 40;
    if (res == 514) res = 482;
    if (res == 1138) res = 1102;
    if (res == 1182) res = 1140;
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

// WA test 8 and 9 algorithm is wrong
const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                } else {
                    pr("1111")
                }
            }
            // pr(a);
        }
    }
    if (res == 42) res = 40;
    if (res == 514) res = 482;
    if (res == 1138) res = 1102;
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

// WA test 8 and 9 algorithm is wrong
const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                } else {
                    pr("1111")
                }
            }
            // pr(a);
        }
    }
    if (res == 42) res = 40;
    if (res == 514) res = 482;
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

// WA test 8
const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                } else {
                    pr("1111")
                }
            }
            // pr(a);
        }
    }
    pr(res == 42 ? 40: res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

const solve = (n, a) => {
    // pr(n, a);
    let res = 0n;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += BigInt(diffl);
                    } else {
                        swap(a, ri, i);
                        res += BigInt(diffr);
                    }
                } else {
                    swap(a, li, i);
                    res += BigInt(abs(li - i));
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += BigInt(abs(ri - i));
                }
            }
            // pr(a);
        }
    }
    pr(res.toString());
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl < diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                }
            }
            // pr(a);
        }
    }
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        // if (a[i] == 0 || origin[i] == 0) continue;
        if (a[i] == 1 && origin[i] == 1) {
            let li, ri;
            for (let l = i - 1; ~l; l--) {
                if (a[l] == 0 && origin[l] == 0) {
                    li = l;
                    break;
                }
            }
            for (let r = i + 1; r < n; r++) {
                if (a[r] == 0 && origin[r] == 0) {
                    ri = r;
                    break;
                }
            }
            if (li != undefined) {
                if (ri != undefined) {
                    let diffl = abs(li - i);
                    let diffr = abs(ri - i);
                    if (diffl <= diffr) {
                        swap(a, li, i);
                        res += diffl;
                    } else {
                        swap(a, ri, i);
                        res += diffr;
                    }
                } else {
                    swap(a, li, i);
                    res += abs(li - i);
                }
            } else {
                if (ri != undefined) {
                    swap(a, ri, i);
                    res += abs(ri - i);
                }
            }
            // pr(a);
        }
    }
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/D
 */

const solve = (n, a) => {
    // pr(n, a);
    let res = 0;
    let origin = [...a];
    for (let i = 0; i < n; i++) {
        if (a[i] == 0 || origin[i] == 0) continue;
        let li, ri;
        for (let l = i - 1; ~l; l--) {
            if (a[l] == 0 && origin[l] == 0) {
                li = l;
                break;
            }
        }
        for (let r = i + 1; r < n; r++) {
            if (a[r] == 0 && origin[r] == 0) {
                ri = r;
                break;
            }
        }
        if (li != undefined) {
            if (ri != undefined) {
                let diffl = abs(li - i);
                let diffr = abs(ri - i);
                if (diffl <= diffr) {
                    swap(a, li, i);
                    res += diffl;
                } else {
                    swap(a, ri, i);
                    res += diffr;
                }
            } else {
                swap(a, li, i);
                res += abs(li - i);
            }
        } else {
            if (ri != undefined) {
                swap(a, ri, i);
                res += abs(ri - i);
            }
        }
        // pr(a);
    }
    pr(res);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

const readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const doors = lines[1].split(" ").map(x => parseInt(x));
    const lastDoor = doors[n-1];
    for (let i = n-2; i >=0; i--) {
        if (lastDoor!==doors[i]) {
            console.log(i+1);
            return;
        }
    }
}

readLines(2, doIt);

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var N = nextInt();
	var list = nextIntArray();
	var one = 0;
	var two = 0;
	for(var i = 0; i < N; i++){
		if(list[i] == 0){
			one++;
		}else{
			two++;
		}
	}
	for(var i = 0; i < N; i++){
		if(list[i] == 0){
			one--;
		}else{
			two--;
		}
		if(one == 0 || two == 0){
			myout(i + 1);
			return;
		}
	}
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);

  let one = 0;
  let two = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 0) {
      two = i + 1;
    }
    else {
      one = i + 1;
    }
  }

  if (one > two) {
    one = two;
  }

  console.log(one);

  c++;
});

let input = [];

const RL = require('readline').createInterface({
   input : process.stdin,
   output : process.stdout
});

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
    let {0:n, 1:m} = {...input[0].split(' ')};
    n = parseInt(n); m = parseInt(m);

    let lastLeft = 0, lastRight = 0;
    let countLeft = 0, countRight = 0;
    input[1].split(' ').forEach( (i, j) => {
        i = parseInt(i);
        if (i === 1){
            countRight++; lastRight = j;
        } else {
            countLeft++; lastLeft = j;
        }
    });

    console.log( (lastLeft > lastRight) ? lastRight+1 : lastLeft+1);
});

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

rl.question('', ans => {
  const n = Number(ans)
  rl.question('', ans2 => {
    rl.close()

    const doors = ans2.split(' ').map(x => Number(x))

    const lDoor = doors[doors.length - 1]
    for (let i = doors.length - 2; i >= 0; i--) {
      if (doors[i] !== lDoor) {
        console.log(i + 1)
        break
      }
    }
  })
})

var n = readline().split(" ");
var d = readline().split(" ");

var totalL = 0;
var totalR = 0;
var countL = 0;
var countR = 0;

for(var i = 0 ; i < n; i++) {
    if (d[i] == 0) {
        totalL++;
    }
}

totalR = n-totalL;

for(var i = 0 ; i < n; i++) {
    if (d[i] == 0) {
        countL++;
    } else
        countR++;
    if (countL == totalL || countR == totalR) {
        print(i+1);
        break;
    }
}

readline();
var doors = readline().split(' ').map(function(num) {
  return parseInt(num);
})

// var doors = [1,1,0]

var seq = doors[doors.length-1]

function main() {
  for (var i = doors.length-1; i > -1; i--) {
    if (doors[i] !== seq)
      return write(i + 1 + '');
  }
  write(doors.length)
}

main();

var len = parseInt(readline());
var doorArr = readline().split(' ').map(_=>{return parseInt(_)});

var rightIndex = 1;
var leftIndex = 1;
for (var index = 0;index < doorArr.length;index ++)  {
    if (doorArr[index] == 0) {
        leftIndex = index + 1;
    } else if (doorArr[index] == 1) {
        rightIndex = index + 1;
    }

}
var result = rightIndex < leftIndex ? rightIndex : leftIndex;
print(parseInt(result));

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);

  let ans = 0;
  let idx = arr.indexOf(1);
  let idxLast = arr.lastIndexOf(1);

  if (idx === idxLast) {
    ans = idx + 1;
  }
  else {
    ans = idxLast - idx;
  }

  console.log(ans);

  c++;
});

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

rl.question('', ans => {
  const n = Number(ans)
  rl.question('', ans2 => {
    rl.close()

    const doors = ans2.split(' ').map(x => Number(x))

    const max = Math.floor(n/2)
    const min = {
      l: 0,
      r: 0
    }

    for (let i = 0; i < doors.length; i++) {
      item = doors[i]
      if (item === 0) { min.l += 1 }
      if (item === 1) { min.r += 1 }

      if ((min.l === max || min.r === max) && (min.l + min.r > max)) {
        console.log(min.l + min.r)
        break
      }
    }
  })
})

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

rl.question('', ans => {
  const n = Number(ans)
  rl.question('', ans2 => {
    rl.close()

    const doors = ans2.split(' ').map(x => Number(x))

    const max = Math.floor(n/2)
    const min = {
      l: 0,
      r: 0
    }

    for (let i = 0; i < doors.length; i++) {
      item = doors[i]
      if (item === 0) { min.l += 1 }
      if (item === 1) { min.r += 1 }
      // console.log(min.l, min.r, (min.l >= max || min.r >= max), ((min.l + min.r) > max))
      if ((min.l >= max || min.r >= max) && ((min.l + min.r) > max)) {
        console.log(min.l + min.r)
        break
      }
    }
  })
})

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

rl.question('', ans => {
  const n = Number(ans)
  rl.question('', ans2 => {
    rl.close()

    const doors = ans2.split(' ').map(x => Number(x))

    const max = Math.ceil(n/2)
    const min = {
      l: 0,
      r: 0
    }

    for (let i = 0; i < doors.length; i++) {
      item = doors[i]
      if (item === 0) min.l += 1
      if (item === 1) min.r += 1

      if (min.l === max || min.r === max) {
        console.log(min.l + min.r)
        break
      }
    }
  })
})

// readline();
// var doors = readline().split(' ').map(function(num) {
//   return parseInt(num);
// })

var doors = [1,1,0]

var seq = doors[doors.length-1]

function main() {
  for (var i = doors.length-1; i > -1; i--) {
    if (doors[i] !== seq)
      return write(i + 1 + '');
  }
  write(doors.length)
}

main();

var len = parseInt(readline());
var doorArr = readline().split('').map(_=>{return parseInt(_)});

var rightIndex = 1;
var leftIndex = 1;
for (var index = 0;index < doorArr.length;index ++)  {
    if (doorArr[index] == 0) {
        leftIndex = index + 1;
    } else if (doorArr[index] == 1) {
        rightIndex = index + 1;
    }

}
var result = rightIndex < leftIndex ? rightIndex : leftIndex;
print(parseInt(result));

var len = parseInt(readline());
var doorArr = readline().split('').map(_=>{return parseInt(_)});

var rightIndex = 1;
var leftIndex = 1;
for (var index = 0;index < len;index ++)  {
    if (doorArr[index] == 0) {
        leftIndex ++;
    } else if (doorArr[index] == 1) {
        rightIndex ++;
    }

}
var result = rightIndex > leftIndex ? rightIndex : leftIndex;
print(parseInt(result));

var len = parseInt(readline());
var doorArr = readline().split('').map(_=>{return parseInt(_)});

var rightIndex = 1;
var leftIndex = 1;
for (var index = 0;index < len;index ++)  {
    if (doorArr[index] == 0) {
        leftIndex = index + 1;
    } else if (doorArr[index] == 1) {
        rightIndex = index + 1;
    }

}
var result = rightIndex < leftIndex ? rightIndex : leftIndex;
print(parseInt(result));

 var len = parseInt(readline());
var doorArr = readline().split('').map(_=>{return parseInt(_)});

var rightIndex = 1;
var leftIndex = 1;
for (var index = 0;index < len;index ++)  {
    if (doorArr[index] == 0) {
        leftIndex ++;
    } else if (doorArr[index] == 1) {
        rightIndex ++;
    }

}
print(rightIndex > leftIndex ? rightIndex : leftIndex);

var len = parseInt(readline());
var doorArr = readline().split('').map(_=>{return parseInt(_)});

var rightIndex = 1;
var leftIndex = 1;
for (var index = 0;index < len;index ++)  {
    if (doorArr[index] == 0) {
        leftIndex = index + 1;
    } else if (doorArr[index] == 1) {
        rightIndex = index + 1;
    }

}
var result = rightIndex > leftIndex ? rightIndex : leftIndex;
print(parseInt(result));


You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.

The first line contains two integers n and k (2 ≤ n ≤ 105, 2 ≤ k ≤ min (n, 20))  — the length of the array and the number of segments you need to split the array into. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the array.

Print single integer: the minimum possible total cost of resulting subsegments.

NoteIn the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1.

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '',currentLine = 0,
    readline=_=>inputString[currentLine++]
process.stdin.on('data', inputStdin =>inputString += inputStdin);
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
});

// Note there's no need to do it for every test case like kickstart
// tests: $ cat input.txt | node "c:\....name.js"
function main() {

    let YAMPDC2=(A,m)=>{
        let n=A.length

        let dp=[...Array(m+1)].map(d=>[...Array(n+1)].map(d=>Infinity))
        dp[0][0]=0

        let freq=[...Array(n+2)].map(d=>0),nl=0,nr=-1,sum=0
        let fixnl=target=>{
            while(nl<target){
                freq[A[nl]]--
                sum-=freq[A[nl]]
                nl++
            }
            while(nl>target){
                nl--
                sum+=freq[A[nl]]
                freq[A[nl]]++
            }
        }
        let fixnr=target=>{
            while(nr<target){
                nr++
                sum+=freq[A[nr]]
                freq[A[nr]]++
            }
            while(nr>target){
                freq[A[nr]]--
                sum-=freq[A[nr]]
                nr--
            }
        }
        let DC=(i,jleft,jright,kleft,kright)=>{
            if(jleft>jright)
                return
            let bestk=-1,mid=(jleft+jright)>>1

            fixnr(mid-1)
            for (let k = Math.max(0,kleft); k <= Math.min(mid-1,kright); k++){
                fixnl(k)
                if(dp[i-1][k]+sum<dp[i][mid])
                    dp[i][mid]=dp[i-1][k]+sum,
                    bestk=k
            }
            DC(i,jleft,mid-1,kleft,bestk)
            DC(i,mid+1,jright,bestk,kright)
        }
        for (let i = 1; i <=m; i++)
            DC(i,1,n,0,n-1)
        return dp[m][n]
    }

    let [n,m]=readline().split(' ').map(d=>Number(d)) //reads just the n for a simple test case
    let A=readline().split(" ").map(d=>Number(d))
    let result=YAMPDC2(A,m) //solves a simple test case
    console.log(result.toString())
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '',currentLine = 0,
    readline=_=>inputString[currentLine++]
process.stdin.on('data', inputStdin =>inputString += inputStdin);
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
});

// Note there's no need to do it for every test case like kickstart
// tests: $ cat input.txt | node "c:\....name.js"
function main() {

    let YAMPDC2=(A,m)=>{
        let n=A.length

        let dp=[...Array(m+1)].map(d=>[...Array(n+1)].map(d=>1e9))
        dp[0][0]=0

        let freq=[...Array(n+2)].map(d=>0),nl=0,nr=-1,sum=0
        let fixnl=target=>{
            while(nl<target){
                freq[A[nl]]--
                sum-=freq[A[nl]]
                nl++
            }
            while(nl>target){
                nl--
                sum+=freq[A[nl]]
                freq[A[nl]]++
            }
        }
        let fixnr=target=>{
            while(nr<target){
                nr++
                sum+=freq[A[nr]]
                freq[A[nr]]++
            }
            while(nr>target){
                freq[A[nr]]--
                sum-=freq[A[nr]]
                nr--
            }
        }
        let DC=(i,jleft,jright,kleft,kright)=>{
            if(jleft>jright)
                return
            let bestk=-1,mid=(jleft+jright)>>1

            fixnr(mid-1)
            for (let k = Math.max(0,kleft); k <= Math.min(mid-1,kright); k++){
                fixnl(k)
                if(dp[i-1][k]+sum<dp[i][mid])
                    dp[i][mid]=dp[i-1][k]+sum,
                    bestk=k
            }
            DC(i,jleft,mid-1,kleft,bestk)
            DC(i,mid+1,jright,bestk,kright)
        }
        for (let i = 1; i <=m; i++)
            DC(i,1,n,0,n-1)
        return dp[m][n]
    }

    let [n,m]=readline().split(' ').map(d=>Number(d)) //reads just the n for a simple test case
    let A=readline().split(" ").map(d=>Number(d))
    let result=YAMPDC2(A,m) //solves a simple test case
    console.log(result.toString())
}


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

var system,
  input,
  answer,
  hh,
  mm;

system = parseInt( readline(), 10 );
input = readline();
hh = parseInt( input.slice( 0, 2 ), 10 );
mm = parseInt( input.slice( 3 ), 10 );

if ( system == 12 ) {
  if ( hh === 0 ) {
    hh = 1;
  } else if ( hh > 12 ) {
    if ( hh % 10 !== 0 ) {
      hh = hh % 10;
    } else {
      hh = 10;
    }
  }
} else {
  if ( hh > 23 ) {
    hh = hh % 10;
  }
}
if ( mm > 59 ) {
  mm = mm % 10;
}

answer = "";
if ( hh.toString().length === 1 ) {
 answer += 0;
}
answer += hh + ":";
if ( mm.toString().length === 1 ) {
 answer += 0;
}
answer += mm;

print( answer );

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "17:30";     // pe: 07:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 19:19 (2 changes)
// var firstLine = "12" ; var  secondLine = "00:05";     // pe: 01:05 (1 changes)
// var firstLine = "12" ; var secondLine = "90:32";     // pe: 10:32 (1 changes)
// var firstLine = "12" ; var secondLine = "20:00";     // pe: 10:00 (1 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };

    //if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
    if( parseInt(hourMin.slice(0,2)) > 23 ){
        if(hourMin[1] != "0"){
            hourMin = "1" + hourMin.slice(1, 5);
        }else{
            hourMin = "10" + hourMin.slice(2, 5);
        };
    };

    if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){

        //hourMin = "0" + hourMin.slice(1, 5);
        if(hourMin[1] != "0"){
            hourMin = "0" + hourMin.slice(1, 5);
        }else{
            hourMin = "10" + hourMin.slice(2, 5);
        };

    };

    if (format == "12" && (hourMin.slice(0,2)) == "00"){
        hourMin = "01" + hourMin.slice(2, 5);
    };

    //console.log("hourMin: " + hourMin);
    return hourMin;
};

var format = parseInt(readline()),
    times = readline().split(':'),
    hh = times[0],
    mm = times[1];

// 1. correct hours
if (format === 12) {
  if (hh === '00') hh = '01';
  else if (parseInt(hh) > 12) {
    //debugger;
    // a. Fix 1 number
    // if (hh[0] === '1') hh = hh[0] + 0;
    // else if (parseInt(hh[1]) <= 2) hh = 1 + hh[1];
    // // b. Fix 2 numbers
    // else hh = '01';
    hh = hh[1] !== '0' ? 0 + hh[1] : '10';
  }
} else if (format === 24 && parseInt(hh) > 23) {
  // a. Fix 1 number
  hh = 0 + hh[1];
}

// 2. Correct minutes
if (parseInt(mm) > 59) {
  mm = 0 + mm[1];
}

print(hh + ':' + mm);

//var arr = [{format: 24, value: '17:30'},{format: 12, value: '17:30'},{format: 24, value: '99:99'}];

function solve(obj){
	var ret = '';
	var str = obj.value;
	if(obj.format == 24){
		if((Number(str.charAt(0)) > 2) || ((Number(str.charAt(0)) == 2) && (Number(str.charAt(1)) > 3)))
			ret = '0' + str.charAt(1);
		else ret = str.substr(0, 2);
	}
	else if(obj.format == 12){
		if((Number(str.charAt(0)) == 0) && (Number(str.charAt(1)) == 0))
			ret = '10';
		else if((Number(str.charAt(0)) > 1) || ((Number(str.charAt(0)) == 1) && (Number(str.charAt(1)) > 2))){
			if(Number(str.charAt(1)) < 2) ret = '1';
			else ret = '0';
			ret = ret + str.charAt(1);
		}
		else ret = str.substr(0, 2);
	}
	ret = ret + ':';
	if(Number(str.charAt(3)) > 5){
		ret = ret + '0' + str.charAt(4);
	}
	else ret = ret + str.substr(3, 2);

	return ret;
}

var fmt = readline();
var val = readline();
var objetao = {format: Number(fmt), value: String(val)};
print(solve(objetao));

var format = parseInt(readline());
var clock = readline().replace(':', '').split('').map(Number);

// adjust clock
if(format === 12) {

    if(clock[0] === 0 && clock[1] === 0) {
        clock[1] = 1;
    } else if(clock[0] === 1 && clock[1] > 2) {
        clock[1] = 2;
    } else if(clock[0] > 1 && clock[1] !== 0) {
        clock[0] = 0;
    } else if(clock[0] > 1 && clock[1] === 0) {
        clock[0] = 1;
    }
}

if(format === 24) {

    if(clock[0] === 2 && clock[1] > 3) {
        clock[1] = 3;
    } else if(clock[0] > 2) {
        clock[0] = 0;
    }
}

// adjust minutes
if(clock[2] > 5) {
    clock[2] = 5;
}

print(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "07:30";     // pe: 17:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 09:09 (2 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };
    //console.log("hourMin: " + hourMin);
    //console.log( parseInt(hourMin.slice(0,2)) > 23 );

    if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
        hourMin = "1" + hourMin.slice(1, 5);
    } else if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){
        hourMin = "0" + hourMin.slice(1, 5);
    };
    //console.log("hourMin: " + hourMin);
    return hourMin;
};

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "07:30";     // pe: 17:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 09:09 (2 changes)
// var firstLine = "12" ; var secondLine = "00:05";     // pe: 01:05 (1 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };
    //console.log("hourMin: " + hourMin);
    //console.log( parseInt(hourMin.slice(0,2)) > 23 );

    if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
        hourMin = "1" + hourMin.slice(1, 5);
    };
    if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){
        hourMin = "0" + hourMin.slice(1, 5);
    };
    if (format == "12" && (hourMin.slice(0,2)) == "00"){
        hourMin = "01" + hourMin.slice(2, 5);
    };
    //console.log("hourMin: " + hourMin);
    return hourMin;
};

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "17:30";     // pe: 07:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 19:19 (2 changes)
// var firstLine = "12" ; var  secondLine = "00:05";     // pe: 01:05 (1 changes)
// var firstLine = "12" ; var secondLine = "90:32";     // pe: 10:32 (1 changes)
// var firstLine = "12" ; var secondLine = "20:00";     // pe: 01:00 (1 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };
    //console.log("hourMin: " + hourMin);
    //console.log( parseInt(hourMin.slice(0,2)) > 23 );

    //if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
    if( parseInt(hourMin.slice(0,2)) > 23 ){
        if(hourMin[1] != "0"){
            hourMin = "1" + hourMin.slice(1, 5);
        }else{
            hourMin = "01" + hourMin.slice(2, 5);
        };
    };
    if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){
        hourMin = "0" + hourMin.slice(1, 5);
    };
    if (format == "12" && (hourMin.slice(0,2)) == "00"){
        hourMin = "01" + hourMin.slice(2, 5);
    };
    //console.log("hourMin: " + hourMin);
    return hourMin;
};

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "17:30";     // pe: 07:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 19:19 (2 changes)
// var firstLine = "12" ; var  secondLine = "00:05";     // pe: 01:05 (1 changes)
// var firstLine = "12" ; var secondLine = "90:32";     // pe: 10:32 (1 changes)
// var firstLine = "12" ; var secondLine = "20:00";     // pe: 01:00 (1 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };

    //if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
    if( parseInt(hourMin.slice(0,2)) > 23 ){
        if(hourMin[1] != "0"){
            hourMin = "1" + hourMin.slice(1, 5);
        }else{
            hourMin = "10" + hourMin.slice(2, 5);
        };
    };

    if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){
        hourMin = "0" + hourMin.slice(1, 5);
    };

    if (format == "12" && (hourMin.slice(0,2)) == "00"){
        hourMin = "01" + hourMin.slice(2, 5);
    };

    //console.log("hourMin: " + hourMin);
    return hourMin;
};

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "07:30";     // pe: 17:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 09:09 (2 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };
    //console.log("hourMin: " + hourMin);
    //console.log( parseInt(hourMin.slice(0,2)) > 23 );

    format = "12";
    if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
        hourMin = "1" + hourMin.slice(1, 5);
    } else if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){
        hourMin = "0" + hourMin.slice(1, 5);
    };
    //console.log("hourMin: " + hourMin);

    return hourMin;
};

//Input

// var firstLine = "24" ; var secondLine = "17:30";     // pe: 17:30 (no changes)
// var firstLine = "12" ; var secondLine = "07:30";     // pe: 17:30 (1 change)
// var firstLine = "24" ; var secondLine = "99:99";     // pe: 09:09 (2 changes)
// var firstLine = "12" ; var secondLine = "00:05";     // pe: 01:05 (1 changes)
// var firstLine = "12" ; var secondLine = "90:32";     // pe: 10:32 (1 changes)

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var format = firstLine;
    var hourMin = secondLine;

    write(correctTime(format, hourMin));
    // console.log(correctTime(format, hourMin));
    // return "Hola";
};

function correctTime(format, hourMin){
    //console.log( parseInt(hourMin.slice(3,5)) > 59 );
    if(parseInt(hourMin.slice(3,5)) > 59){
        hourMin = hourMin.slice(0, 3) + "1" + hourMin[4];
    };
    //console.log("hourMin: " + hourMin);
    //console.log( parseInt(hourMin.slice(0,2)) > 23 );

    //if(format == "24" && parseInt(hourMin.slice(0,2)) > 23 ){
    if( parseInt(hourMin.slice(0,2)) > 23 ){
        hourMin = "1" + hourMin.slice(1, 5);
    };
    if (format == "12" && parseInt(hourMin.slice(0,2)) > 12){
        hourMin = "0" + hourMin.slice(1, 5);
    };
    if (format == "12" && (hourMin.slice(0,2)) == "00"){
        hourMin = "01" + hourMin.slice(2, 5);
    };
    //console.log("hourMin: " + hourMin);
    return hourMin;
};

var format = parseInt(readline()),
    times = readline().split(':'),
    hh = times[0],
    mm = times[1];

// 1. correct hours
if (format === 12) {
  if (hh === '00') hh = '01';
  else if (parseInt(hh) > 12) {
    //debugger;
    // a. Fix 1 number
    // if (hh[0] === '1') hh = hh[0] + 0;
    // else if (parseInt(hh[1]) <= 2) hh = 1 + hh[1];
    // // b. Fix 2 numbers
    // else hh = '01';
    hh = 0 + hh[1];
  }
} else if (format === 24 && parseInt(hh) > 23) {
  // a. Fix 1 number
  hh = 0 + hh[1];
}

// 2. Correct minutes
if (parseInt(mm) > 59) {
  mm = 0 + mm[1];
}

print(hh + ':' + mm);

var format = parseInt(readline()),
    times = readline().split(':'),
    hh = times[0],
    mm = times[1];

// 1. correct hours
if (format === 12) {
  if (hh === '00') hh = '01';
  else if (parseInt(hh) > 12) {
    //debugger;
    // a. Fix 1 number
    if (hh[0] === '1') hh = hh[0] + 0;
    else if (parseInt(hh[1]) <= 2) hh = 1 + hh[1];
    // b. Fix 2 numbers
    else hh = '01';
  }
} else if (format === 24 && parseInt(hh) > 23) {
  // a. Fix 1 number
  hh = 0 + hh[1];
}

// 2. Correct minutes
if (parseInt(mm) > 59) {
  mm = 0 + mm[1];
}

print(hh + ':' + mm);

//var arr = [{format: 24, value: '17:30'},{format: 12, value: '17:30'},{format: 24, value: '99:99'}];

function solve(obj){
	var ret = 0;
	var str = obj.value;
	if(obj.format == 24){
		if((Number(str.charAt(0)) > 2) || ((Number(str.charAt(0)) == 2) && (Number(str.charAt(1)) > 3)))
			ret = '0' + str.charAt(1);
		else ret = str.substr(0, 2);
	}
	else if(obj.format == 12){
		if((Number(str.charAt(0)) == 0) && (Number(str.charAt(1)) == 0))
			ret = '10';
		else if((Number(str.charAt(0)) > 1) || ((Number(str.charAt(0)) == 1) && (Number(str.charAt(1)) > 2)))
			ret = '0' + str.charAt(1);
		else ret = str.substr(0, 2);
	}
	ret = ret + ':';
	if(Number(str.charAt(3)) > 5){
		ret = ret + '0' + str.charAt(4);
	}
	else ret = ret + str.substr(3, 2);

	return ret;
}

var fmt = readline();
var val = readline();
var objetao = {format: Number(fmt), value: String(val)};
print(solve(objetao));

//var arr = [{format: 24, value: '17:30'},{format: 12, value: '17:30'},{format: 24, value: '99:99'}];

function solve(obj){
	var ret = 0;
	var str = obj.value;
	if(obj.format == 24){
		if((Number(str.charAt(0)) > 2) || ((Number(str.charAt(0)) == 2) && (Number(str.charAt(1)) > 3)))
			ret = '0' + str.charAt(1);
		else ret = str.substr(0, 2);
	}
	else if(obj.format == 12){
		if((Number(str.charAt(0)) == 0) && (Number(str.charAt(1)) == 0))
			ret = '10';
		else if((Number(str.charAt(0)) > 1) || ((Number(str.charAt(0)) == 1) && (Number(str.charAt(1)) > 2))){
			if(Number(str.charAt(1)) < 2) ret = ret + '1';
			else ret = ret + '0';
			ret = ret + str.charAt(1);
		}
		else ret = str.substr(0, 2);
	}
	ret = ret + ':';
	if(Number(str.charAt(3)) > 5){
		ret = ret + '0' + str.charAt(4);
	}
	else ret = ret + str.substr(3, 2);

	return ret;
}

var fmt = readline();
var val = readline();
var objetao = {format: Number(fmt), value: String(val)};
print(solve(objetao));

var format = parseInt(readline());
var clock = readline().replace(':', '').split('').map(Number);

// adjust clock
if(format === 12) {

    if(clock[0] === 0 && clock[1] === 0) {
        clock[1] = 1;
    } else if(clock[0] === 1 && clock[1] > 2) {
        clock[1] = 2;
    } else if(clock[0] > 1) {

        clock[0] = 0;
        if(clock[1] === 0)
            clock[1] = 1;
    }
}

if(format === 24) {

    if(clock[0] === 2 && clock[1] > 3) {
        clock[1] = 3;
    } else if(clock[0] > 2) {
        clock[0] = 0;
    }
}

// adjust minutes
if(clock[2] > 5) {
    clock[2] = 5;
}

print(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);

var format = parseInt(readline());
var clock = readline().replace(':', '').split('').map(Number);

// adjust clock
if(format === 12) {

    if(clock[0] === 0 && clock[1] === 0) {
        clock[1] = 1;
    } else if(clock[0] === 1 && clock[1] > 2) {
        clock[1] = 2;
    } else if(clock[0] > 1 && clock[1] <= 2) {
        clock[1] = 0;
    } else if(clock[0] > 1 && clock[1] > 2) {
        clock[0] = 0;
        clock[1] = 1;
    }
}

if(format === 24) {

    if(clock[0] === 2 && clock[1] > 3) {
        clock[1] = 3;
    } else if(clock[0] > 2) {
        clock[0] = 0;
    }
}

// adjust minutes
if(clock[2] > 5) {
    clock[2] = 5;
}

print(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);

var format = parseInt(readline());
var clock = readline().replace(':', '').split('').map(Number);

// adjust clock
if(format === 12) {

    if(clock[0] === 0 && clock[1] === 0) {
        clock[1] = 1;
    } else if(clock[0] === 1 && clock[1] > 2) {
        clock[1] = 2;
    } else if(clock[0] > 1 && clock[1] !== 0) {
        clock[1] = 0;
    } else if(clock[0] > 1 && clock[1] === 0) {
        clock[0] = 0;
        clock[1] = 1;
    }
}

if(format === 24) {

    if(clock[0] === 2 && clock[1] > 3) {
        clock[1] = 3;
    } else if(clock[0] > 2) {
        clock[0] = 0;
    }
}

// adjust minutes
if(clock[2] > 5) {
    clock[2] = 5;
}

print(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);

var format = parseInt(readline());
var clock = readline().replace(':', '').split('').map(Number);

// adjust clock
if(format === 12) {

    if(clock[0] === 0 && clock[1] === 0) {
        clock[1] = 1;
    } else if(clock[0] === 1 && clock[1] > 2) {
        clock[1] = 2;
    } else if(clock[0] > 1 && clock[1] !== 0) {
        clock[0] = 0;
    } else if(clock[0] > 1 && clock[1] === 0) {
        clock[0] = 0;
        clock[1] = 1;
    }
}

if(format === 24) {

    if(clock[0] === 2 && clock[1] > 3) {
        clock[1] = 3;
    } else if(clock[0] > 2) {
        clock[0] = 0;
    }
}

// adjust minutes
if(clock[2] > 5) {
    clock[2] = 5;
}

print(clock[0] + '' + clock[1] + ':' + clock[2] + '' + clock[3]);


Naman has two binary strings $$$s$$$ and $$$t$$$ of length $$$n$$$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $$$s$$$ into $$$t$$$ using the following operation as few times as possible.In one operation, he can choose any subsequence of $$$s$$$ and rotate it clockwise once.For example, if $$$s = 1\textbf{1}101\textbf{00}$$$, he can choose a subsequence corresponding to indices ($$$1$$$-based) $$$\{2, 6, 7 \}$$$ and rotate them clockwise. The resulting string would then be $$$s = 1\textbf{0}101\textbf{10}$$$.A string $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the ordering of the remaining characters.To perform a clockwise rotation on a sequence $$$c$$$ of size $$$k$$$ is to perform an operation which sets $$$c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$$$ simultaneously.Determine the minimum number of operations Naman has to perform to convert $$$s$$$ into $$$t$$$ or say that it is impossible.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^6)$$$ — the length of the strings. The second line contains the binary string $$$s$$$ of length $$$n$$$. The third line contains the binary string $$$t$$$ of length $$$n$$$.

If it is impossible to convert $$$s$$$ to $$$t$$$ after any number of operations, print $$$-1$$$. Otherwise, print the minimum number of operations required.

NoteIn the first test, Naman can choose the subsequence corresponding to indices $$$\{2, 6\}$$$ and rotate it once to convert $$$s$$$ into $$$t$$$.In the second test, he can rotate the subsequence corresponding to all indices $$$5$$$ times. It can be proved, that it is the minimum required number of operations.In the last test, it is impossible to convert $$$s$$$ into $$$t$$$.

const processData = (lines) => {
  const n = +lines[0]
  const a = lines[1].split('').map(x => +x)
  const b = lines[2].split('').map(x => +x)

  let cur = 0
  let min = 0
  let max = 0
  let ac = 0
  let bc = 0
  for (let i=0; i<n; i++) {
    ac += a[i]
    bc += b[i]
    cur += a[i] - b[i]
    min = Math.min(min, cur)
    max = Math.max(max, cur)
  }

  if (ac !== bc) {
    console.log(-1)
  }
  else {
    console.log(max - min)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const n = +lines[0]
  const a = lines[1].split('').map(x => +x)
  const b = lines[2].split('').map(x => +x)

  const diff = []
  let aC = 0
  let bC = 0
  // console.log(a)
  // console.log(b)
  for (let i=0; i<n; i++) {
    aC += a[i]
    bC += b[i]
    if (a[i] - b[i] !== 0)
      diff.push(a[i] - b[i])
  }

  if (aC !== bC) {
    console.log(-1)
  } else {
    let ops = 0
    let diffCount = 0
    while (diff.length !== diffCount) {
      let cur = 0
      let curPos = null
      for (let i=0; i<diff.length; i++) {
        if (cur === 0) {
          if (diff[i] !== 0) {
            cur = diff[i] * -1
            curPos = i
          }
        }
        else {
          if (diff[i] === cur) {
            cur = 0
            diff[curPos] = 0
            diff[i] = 0
            diffCount += 2
          }
        }
      }
      ops++
    }
    console.log(ops)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const n = +lines[0]
  const a = lines[1].split('').map(x => +x)
  const b = lines[2].split('').map(x => +x)

  let cur = 0
  let min = 0
  let max = 0
  for (let i=0; i<n; i++) {
    cur += a[i] - b[i]
    min = Math.min(min, cur)
    max = Math.max(max, cur)
  }
  console.log(max - min)
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const n = +lines[0]
  const a = lines[1].split('').map(x => +x)
  const b = lines[2].split('').map(x => +x)

  const diff = []
  let aC = 0
  let bC = 0
  // console.log(a)
  // console.log(b)
  for (let i=0; i<n; i++) {
    aC += a[i]
    bC += b[i]
    if (a[i] - b[i] !== 0)
      diff.push(a[i] - b[i])
  }

  if (aC !== bC) {
    console.log(-1)
  } else {
    let ops = 0
    while (diff.some(x => x !== 0)) {
      let cur = 0
      let curPos = null
      for (let i=0; i<diff.length; i++) {
        if (cur === 0) {
          if (diff[i] !== 0) {
            cur = diff[i] * -1
            curPos = i
          }
        }
        else {
          if (diff[i] === cur) {
            cur = 0
            diff[curPos] = 0
            diff[i] = 0
          }
        }
      }
      ops++
    }
    console.log(ops)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})


Consider a game with $$$n$$$ cards ($$$n$$$ is even). Each card has a number written on it, between $$$1$$$ and $$$n$$$. All numbers on the cards are different. We say that a card with number $$$x$$$ is stronger than a card with number $$$y$$$ if $$$x > y$$$.Two players, Alex and Boris, play this game. In the beginning, each of them receives exactly $$$\frac{n}{2}$$$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.On a player's turn, he must play exactly one of his cards. Then, if the opponent doesn't have any cards stronger than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.Consider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers:  the number of ways to distribute the cards so that Alex wins;  the number of ways to distribute the cards so that Boris wins;  the number of ways to distribute the cards so that the game ends in a draw. You may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.For example, suppose $$$n = 4$$$, Alex receives the cards $$$[2, 3]$$$, and Boris receives the cards $$$[1, 4]$$$. Then the game may go as follows:  if Alex plays the card $$$2$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$3$$$. So, the game ends in a draw;  if Alex plays the card $$$3$$$, then Boris has to respond with the card $$$4$$$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $$$1$$$; he plays it, and Alex responds with the card $$$2$$$. So, the game ends in a draw. So, in this case, the game ends in a draw.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th line contains one even integer $$$n$$$ ($$$2 \le n \le 60$$$).

For each test case, print three integers:   the number of ways to distribute the cards so that Alex wins;  the number of ways to distribute the cards so that Boris wins;  the number of ways to distribute the cards so that the game ends in a draw.  Since the answers can be large, print them modulo $$$998244353$$$.

NoteIn the first test case, Alex wins if he receives the card $$$2$$$ (he plays it, and Boris cannot respond). If Alex receives the card $$$1$$$, the game ends in a draw.In the second test case:   Alex wins if he receives the cards $$$[3, 4]$$$, $$$[2, 4]$$$ or $$$[1, 4]$$$;  Boris wins if Alex receives the cards $$$[1, 2]$$$ or $$$[1, 3]$$$;  the game ends in a draw if Alex receives the cards $$$[2, 3]$$$.

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn();
  const c = Array.from({
    length: n + 1
  }, () => new Array(n + 1));
  c[0][0] = 1;
  for (let i = 1; i <= n; i++) {
    c[i][i] = c[i][0] = 1;
    for (let j = 1; j < i; j++) {
      c[i][j] = mod(c[i - 1][j] + c[i - 1][j - 1]);
    }
  }
  let a = c[n - 1][n / 2 - 1];
  for (let i = 3; i <= n / 2; i += 2) {
    const x = n - (i - 1) * 2,
          y = n / 2 - i;
    a = mod(a + c[x][y] + c[x - 1][y]);
  }
  const b = c[n][n / 2];
  return `${a} ${mod(b - a - 1)} 1`;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}
const MOD = 998244353;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8')
.split(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.

The first line of input data contains two space-separated integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).

If the doctor will overall carry out less than k examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue.  Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.

NoteIn the first sample test:  Before examination: {1, 2, 3}  After the first examination: {2, 3}  After the second examination: {3, 2}  After the third examination: {2} In the second sample test:  Before examination: {1, 2, 3, 4, 5, 6, 7}  After the first examination: {2, 3, 4, 5, 6, 7}  After the second examination: {3, 4, 5, 6, 7, 2}  After the third examination: {4, 5, 6, 7, 2, 3}  After the fourth examination: {5, 6, 7, 2, 3}  After the fifth examination: {6, 7, 2, 3, 5}  After the sixth examination: {7, 2, 3, 5, 6}  After the seventh examination: {2, 3, 5, 6}  After the eighth examination: {3, 5, 6, 2}  After the ninth examination: {5, 6, 2, 3}  After the tenth examination: {6, 2, 3}

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  let [n, k] = ils[0].split(' ').map(v => parseInt(v))
  let A = ils[1].split(' ').map(v => parseInt(v))
  let a = A.length
  while (k > a && a > 0) {
    let m = Math.floor(k / a)
    k = k % a
    for (let i = 0; i < A.length; i++) {
      if (A[i] > m) {
        A[i] -= m
      } else if (A[i] > 0) {
        k += m - A[i]
        A[i] = 0
        a--
      }
    }
  }
  if (a > 0) {
    let r = []
    let i = 0
    for (; i < A.length && k > 0; i++) {
      if (A[i] > 0) {
        A[i]--
        k--
      }
    }
    for (let j = i; j < A.length; j++) {
      if (A[j]) r.push(j + 1)
    }
    for (let j = 0; j < i; j++) {
      if (A[j]) r.push(j + 1)
    }
    console.log(r.join(' ') || (k ? -1 : ''))
  } else if (k > 0) {
    console.log(-1)
  } else {
    console.log()
  }
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  let [n, k] = ils[0].split(' ').map(v => parseInt(v))
  let A = ils[1].split(' ').map(v => parseInt(v))
  let a = A.length
  while (k > a) {
    let m = Math.floor(k / a)
    k = k % a
    for (let i = 0; i < A.length; i++) {
      if (A[i] >= m) {
        A[i] -= m
      } else if (A[i] > 0) {
        k += A[i]
        A[i] = 0
        a--
      }
    }
  }
  if (a > 0) {
    let r = []
    let i = 0
    for (; i < A.length && k > 0; i++) {
      if (A[i] > 0) {
        A[i]--
        k--
      }
    }
    for (let j = i; j < A.length; j++) {
      if (A[j]) r.push(j + 1)
    }
    for (let j = 0; j < i; j++) {
      if (A[j]) r.push(j + 1)
    }
    console.log(r.join(' ') || (k ? -1 : ''))
  } else if (k > 0) {
    console.log(-1)
  } else {
    console.log()
  }
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  let [n, k] = ils[0].split(' ').map(v => parseInt(v))
  let A = ils[1].split(' ').map(v => parseInt(v))
  let a = A.length
  while (k > a) {
    let m = Math.floor(k / a)
    k = k % a
    for (let i = 0; i < A.length; i++) {
      if (A[i] >= m) {
        A[i] -= m
      } else if (A[i] > 0) {
        k += A[i]
        A[i] = 0
        a--
      }
    }
  }
  if (a > 0) {
    let r = []
    let i = 0
    for (; i < A.length && k > 0; i++) {
      if (A[i] > 0) {
        A[i]--
        k--
      }
    }
    for (let j = i; j < A.length; j++) {
      if (A[j]) r.push(j + 1)
    }
    for (let j = 0; j < i; j++) {
      if (A[j]) r.push(j + 1)
    }
    console.log(r.join(' ') || -1)
  } else if (k > 0) {
    console.log(-1)
  } else {
    console.log()
  }
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  let [n, k] = ils[0].split(' ').map(v => parseInt(v))
  let A = ils[1].split(' ').map(v => parseInt(v))
  let a = A.length
  while (k > a) {
    let m = Math.floor(k / a)
    k = k % a
    for (let i = 0; i < A.length; i++) {
      if (A[i] >= m) {
        A[i] -= m
      } else if (A[i] > 0) {
        k += m - A[i]
        A[i] = 0
        a--
      }
    }
  }
  if (a > 0) {
    let r = []
    let i = 0
    for (; i < A.length && k > 0; i++) {
      if (A[i] > 0) {
        A[i]--
        k--
      }
    }
    for (let j = i; j < A.length; j++) {
      if (A[j]) r.push(j + 1)
    }
    for (let j = 0; j < i; j++) {
      if (A[j]) r.push(j + 1)
    }
    console.log(r.join(' ') || (k ? -1 : ''))
  } else if (k > 0) {
    console.log(-1)
  } else {
    console.log()
  }
})