exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
listlengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED
|
89f3d903fb2cab55fc43f4d38e79baed
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
import java.lang.Math;
public final class Solution {
static int ret_ans(ArrayList<Integer> ones, ArrayList<Integer> zeroes, int dp[][], int i, int j) {
if (i == ones.size()) {
return 0;
} else if (j == zeroes.size()) {
return -1;
} else if (dp[i][j] != 1000000000) {
return dp[i][j];
} else {
int val1 = ret_ans(ones, zeroes, dp, i, j + 1);
int val2 = ret_ans(ones, zeroes, dp, i + 1, j + 1);
// System.out.println(ones.get(i) + " " + zeroes.get(j) + " " + val1 + " " +
// val2);
int MINI = val1;
if (val2 != -1) {
if (MINI == -1) {
MINI = Math.abs(zeroes.get(j) - ones.get(i)) + val2;
} else {
MINI = Math.min(MINI, Math.abs(zeroes.get(j) - ones.get(i)) + val2);
}
}
dp[i][j] = MINI;
return MINI;
}
}
public static void main(String[] args) throws IOException {
FastScanner input = new FastScanner(false);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
ArrayList<Integer> ones = new ArrayList<>();
ArrayList<Integer> zeroes = new ArrayList<>();
for (int i = 0; i < n; i++) {
int val = input.nextInt();
if (val == 0) {
zeroes.add(i);
} else {
ones.add(i);
}
}
int n1 = ones.size();
int m = zeroes.size();
if (n1 == 0) {
out.println(0);
out.flush();
} else {
int dp[][] = new int[n1][m];
for (int i = 0; i < n1; i++) {
for (int j = 0; j < m; j++) {
dp[i][j] = 1000000000;
}
}
int ans = ret_ans(ones, zeroes, dp, 0, 0);
out.println(ans);
out.flush();
}
}
private static class FastScanner {
private final int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
private FastScanner(boolean usingFile) throws IOException {
if (usingFile)
din = new DataInputStream(new FileInputStream("path"));
else
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private short nextShort() throws IOException {
short ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = (short) (ret * 10 + c - '0');
while ((c = read()) >= '0' && c <= '9');
if (neg)
return (short) -ret;
return ret;
}
private int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
private char nextChar() throws IOException {
byte c = read();
while (c <= ' ')
c = read();
return (char) c;
}
private String nextString() throws IOException {
StringBuilder ret = new StringBuilder();
byte c = read();
while (c <= ' ')
c = read();
do {
ret.append((char) c);
} while ((c = read()) > ' ');
return ret.toString();
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
de65e656650d7d28ca47b55bde038ca9
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class cf {
static Reader sc = new Reader();
// static PrintWriter out = new PrintWriter(System.out);
static int mod = (int) 1e9 + 7;
public static void main(String[] args) throws FileNotFoundException {
int n = sc.ni();
int[] arr = sc.nai(n);
ArrayList<Integer> zeroes = new ArrayList<>();
ArrayList<Integer> ones = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
zeroes.add(i);
else
ones.add(i);
}
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(dp[i], -1);
int ans = solve(0, 0, zeroes, ones, dp);
System.out.println(ans);
// out.close();
}
private static int solve(int zi, int oi, ArrayList<Integer> zeroes, ArrayList<Integer> ones, int[][] dp) {
if (oi == ones.size())
return 0;
if (zi == zeroes.size()) {
return 9999999;
}
if (dp[zi][oi] != -1)
return dp[zi][oi];
int sa1 = ((zeroes.size() - zi) > (ones.size() - oi)) ? solve(zi + 1, oi, zeroes, ones, dp) : 9999999;
int sa2 = Math.abs(zeroes.get(zi) - ones.get(oi)) + solve(zi + 1, oi + 1, zeroes, ones, dp);
// System.out.println(zi + " " + oi + " " + sa1 + " " + sa2);
return dp[zi][oi] = Math.min(sa1, sa2);
}
static void shuffleSort(int[] arr) {
// shuffle
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
int j = rand.nextInt(i + 1);
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Arrays.sort(arr);
}
static ArrayList<Integer> sieve(int n) {
ArrayList<Integer> primes = new ArrayList<>();
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i < n; i++) {
if (isPrime[i])
primes.add(i);
}
return primes;
}
static class Reader {
BufferedReader br;
StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
Reader(File f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] nai(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
char[][] nmc(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++) {
String str = sc.next();
for (int j = 0; j < m; j++) {
map[i][j] = str.charAt(j);
}
}
return map;
}
int[][] nmi(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = ni();
}
}
return map;
}
long[][] nml(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = nl();
}
}
return map;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
964c302bd1f01afac728ead80360f82d
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CodeForces {
public static void main(String[] args) throws IOException {
reader input = new reader();
PrintWriter output = new PrintWriter(System.out);
//BufferedReader bf = new BufferedReader(new FileReader("input.txt"));
//PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
//StringTokenizer stk = new StringTokenizer(bf.readLine());
//int n=Integer.parseInt(stk.nextToken());
int n=input.nextInt();
ArrayList<Integer>seated=new ArrayList<>();
ArrayList<Integer>empty=new ArrayList<>();
for(int i=0;i<n;i++){
int x=input.nextInt();
if(x==1)
seated.add(i);
else
empty.add(i);
}
if(seated.size()==0)
output.println(0);
else{
output.println(helper(seated,empty));
}
output.close();
}
public static long helper(ArrayList<Integer>seated,ArrayList<Integer>empty){
long dp[][]=new long[seated.size()+1][empty.size()+1];
for(int i=1;i<= seated.size();i++){
dp[i][i]=dp[i-1][i-1]+Math.abs(seated.get(i-1)-empty.get(i-1));
for(int j=i+1;j<= empty.size();j++){
dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(seated.get(i-1)-empty.get(j-1)));
}
}
return dp[seated.size()][empty.size()];
}
public static int GCD(int a,int b){
if(a==0)
return b;
else
return GCD(b%a,a);
}
public static boolean isPrime(long num){
if(num==1)
return false;
else if(num==2||num==3)
return true;
else if(num%2==0||num%3==0)
return false;
else{
for(long i=5;i*i<=num;i+=6){
if(num%i==0||num%(i+2)==0)
return false;
}
}
return true;
}
public static void mergesort(long arr[],int start,int end){//start and end must be indexes
if(start<end) {
int mid=(start+end)/2;
mergesort(arr,start,mid);
mergesort(arr, mid+1, end);
merge(arr, start,mid,end);
}
}
public static void merge(long arr[],int start,int mid,int end){
int lsize=mid-start+1,rsize=end-mid;
long l[]=new long[lsize],r[]=new long[rsize];
for(int i=start;i<=mid;i++){
l[i-start]=arr[i];
}
for(int i=mid+1;i<=end;i++){
r[i-mid-1]=arr[i];
}
int i=0,j=0,k=start;
while(i<lsize&&j<rsize){
if(l[i]<=r[j]){
arr[k++]=l[i++];
}else{
arr[k++]=r[j++];
}
}
while(i<lsize)
arr[k++]=l[i++];
while(j<rsize)
arr[k++]=r[j++];
}
}
class Pair{
int a,b;
Pair(int a,int b){
this.a=a;
this.b=b;
}
}
class Edge{
int src,dest,weight;
Edge(int src,int dest,int weight){
this.src=src;
this.dest=dest;
this.weight=weight;
}
}
class TempEdge{
int vertex;
long distance;
TempEdge(int vertex,long distance){
this.vertex=vertex;
this.distance=distance;
}
}
//Undirected Graph
class UGraph{
ArrayList<ArrayList<Edge>>graph;
int vertex;
UGraph(int vertex){
this.vertex=vertex;
graph=new ArrayList<>();
for(int i=0;i<vertex;i++){
graph.add(new ArrayList<>());
}
}
void addEdge(int u,int v){
graph.get(u).add(new Edge(u,v,0));
graph.get(v).add(new Edge(v,u,0));
}
void addEdge(int u,int v,int weight){
graph.get(u).add(new Edge(u,v,weight));
graph.get(v).add(new Edge(v,u,weight));
}
ArrayList<Integer> BFS(int source){
boolean visited[]=new boolean[vertex];
ArrayList<Integer>ans=new ArrayList<>();
LinkedList<Integer>q=new LinkedList<>();
q.add(source);
visited[source]=true;
while(!q.isEmpty()){
int x=q.removeFirst();
ans.add(x);
for(Edge i:graph.get(x)){
if(!visited[i.dest]){
q.add(i.dest);
visited[i.dest]=true;
}
}
}
return ans;
}
ArrayList<Integer> BFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
ArrayList<Integer>ans=new ArrayList<>();
for(int i=0;i<vertex;i++){
if(!visited[i]){
ArrayList<Integer>temp=BFS(i);
for(int j:temp)
ans.add(j);
}
}
return ans;
}
int connectedComponentsBFS(){
boolean visited[]=new boolean[vertex];
int count=0;
for(int i=0;i<vertex;i++){
if(!visited[i]){
count++;
BFS(i);
}
}
return count;
}
void DFS(int source){
boolean visited[]=new boolean[vertex];
DFSHelper(source,visited);
System.out.println();
}
void DFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
for(int i=0;i<vertex;i++){
if(!visited[i]){
DFSHelper(i,visited);
System.out.println();
}
}
}
void DFSHelper(int source,boolean visited[]){
visited[source]=true;
System.out.print(source+" ");
for(Edge i:graph.get(source)){
if(!visited[i.dest]){
DFSHelper(i.dest,visited);
}
}
}
boolean detectCycleDFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
for (int i=0;i<vertex;i++){
if(!visited[i]){
if(detectCycleDFSHelper(i,-1,visited))
return true;
}
}
return false;
}
boolean detectCycleDFSHelper(int source,int parent,boolean visited[]){
visited[source]=true;
for(Edge i:graph.get(source)){
if(!visited[i.dest]){
if(detectCycleDFSHelper(i.dest,source,visited))
return true;
}
if(i.dest!=parent)
return true;
}
return false;
}
boolean detectCycleBFS(){//O(V+E)
boolean visited[]=new boolean[vertex];
for (int i=0;i<vertex;i++){
if(!visited[i]){
if(detectCycleBFSHelper(i,visited))
return true;
}
}
return false;
}
boolean detectCycleBFSHelper(int source,boolean visited[]){
int parent[]=new int[vertex];
Arrays.fill(parent,-1);
LinkedList<Integer>q=new LinkedList<>();
q.add(source);
visited[source]=true;
while(!q.isEmpty()){
int x=q.removeFirst();
for(Edge i:graph.get(x)){
if(!visited[i.dest]){
q.add(i.dest);
visited[i.dest]=true;
parent[i.dest]=x;
}
else{
if(parent[x]!=i.dest)
return true;
}
}
}
return false;
}
int primsMST(){
boolean MST[]=new boolean[vertex];
TempEdge distarr[]=new TempEdge[vertex];//MST edge stores least distance of a vertex to the MST
for(int i=0;i<vertex;i++) {
distarr[i] = new TempEdge(i, Integer.MAX_VALUE);
}
distarr[0].distance=0;
// Use TreeSet instead of PriorityQueue as the remove function of the PQ is O(n) in java
TreeSet<TempEdge>q=new TreeSet<>((a,b)->(int)(a.distance-b.distance));
for(int i=0;i<vertex;i++) {
q.add(distarr[i]);
}
int ans=0;
while(!q.isEmpty()){
TempEdge x=q.pollFirst();
ans+=x.distance;
MST[x.vertex]=true;//Adding in MST
for(Edge i:graph.get(x.vertex)){
if(!MST[i.dest]){//Vertex not present in MST
if(distarr[i.dest].distance>i.weight){//Updating smallest distance from MST vertices to i.dest
q.remove(distarr[i.dest]);
distarr[i.dest].distance=i.weight;
q.add(distarr[i.dest]);
}
}
}
}
return ans;
}
long [] dikstra(int source){
long ans[]=new long[vertex];
boolean visited[]=new boolean[vertex];
Arrays.fill(ans,Integer.MAX_VALUE);
ans[source]=0;
//TreeSet may be used as done in prims if removal is required
PriorityQueue<TempEdge>pq=new PriorityQueue<>((a,b)-> (int) (a.distance-b.distance));
int count=0;
pq.add(new TempEdge(source,ans[source]));
while(count!=vertex-1){//On doing vertex-1 times, last vertex is automatically finalised
TempEdge x= pq.poll();
if(!visited[x.vertex]){
visited[x.vertex]=true;
count++;
for(Edge i:graph.get(x.vertex)){
/*Checking visited is not necessary as the won't affect the distance in any case
but will affect the heap*/
if(!visited[i.dest] && ans[i.dest]>ans[x.vertex]+i.weight){
ans[i.dest]=ans[x.vertex]+i.weight;
pq.add(new TempEdge(i.dest,ans[i.dest]));
}
}
}
}
return ans;
}
long[] bellmanford(int source){
long ans[]=new long[vertex];
ans[source]=0;
for(int i=0;i<vertex-1;i++){//Considering paths of length 1 to paths of length (v-1) from source
for(int j=0;j<vertex;j++){
for(Edge k:graph.get(j)){
if(ans[k.dest]>ans[k.src]+ans[k.weight])
ans[k.dest]=ans[k.src]+ans[k.weight];
}
}
}
return ans;
}
}
//Directed non-weighted Graph
class DGraph{
ArrayList<ArrayList<Edge>>graph;
int vertex;
DGraph(int vertex){
this.vertex=vertex;
graph=new ArrayList<>();
for(int i=0;i<vertex;i++){
graph.add(new ArrayList<>());
}
}
void addEdge(int src,int dest){
graph.get(src).add(new Edge(src,dest,0));
}
void addEdge(int src,int dest,int weight){
graph.get(src).add(new Edge(src,dest,weight));
}
boolean detectCycleDFS(){
boolean visited[]=new boolean[vertex];
boolean recst[]=new boolean[vertex];
for(int i=0;i<vertex;i++){
if(!visited[i]){
if(detectCycleDFSHelper(i,visited,recst))
return true;
}
}
return false;
}
boolean detectCycleDFSHelper(int index,boolean visited[],boolean recst[]){
visited[index]=true;
recst[index]=true;
for(Edge i:graph.get(index)){
if(!visited[i.dest]){
if(detectCycleDFSHelper(i.dest,visited,recst))
return true;
}else{
if(recst[i.dest])//Back edge present
return true;
}
}
recst[index]=false;
return false;
}
ArrayList<Integer> topologicalSortingBFS(){//Kahn's Algorithm which is valid only for directed acyclic graphs
ArrayList<Integer>ans=new ArrayList<>();
int indegree[]=new int[vertex];
for(int i=0;i<vertex;i++){
for(Edge j:graph.get(i)){
indegree[j.dest]++;
}
}
LinkedList<Integer>q=new LinkedList<>();
for(int i=0;i<vertex;i++){
if(indegree[i]==0)
q.add(i);
}
while(!q.isEmpty()){
int i=q.removeFirst();
ans.add(i);
for(Edge x:graph.get(i)){
if(--indegree[x.dest]==0){
q.add(x.dest);
}
}
}
return ans;
}
boolean detectCycleTopologicalSort(){
int count=0;
int indegree[]=new int[vertex];
for(int i=0;i<vertex;i++){
for(Edge j:graph.get(i)){
indegree[j.dest]++;
}
}
LinkedList<Integer>q=new LinkedList<>();
for(int i=0;i<vertex;i++){
if(indegree[i]==0)
q.add(i);
}
while(!q.isEmpty()){
int i=q.removeFirst();
count++;
for(Edge x:graph.get(i)){
if(--indegree[x.dest]==0){
q.add(x.dest);
}
}
}
return (count!=vertex);
}
ArrayList<Integer> topologicalSortingDFS(){
boolean visited[]=new boolean[vertex];
ArrayDeque<Integer>recst=new ArrayDeque<>();
for(int i=0;i<vertex;i++){
if(!visited[i]){
topologicalSortingDFSHelper(i,visited,recst);
}
}
ArrayList<Integer>ans=new ArrayList<>();
while(!recst.isEmpty())
ans.add(recst.pop());
return ans;
}
void topologicalSortingDFSHelper(int index,boolean visited[],ArrayDeque<Integer>recst){
visited[index]=true;
for(Edge i:graph.get(index)){
if(!visited[i.dest])
topologicalSortingDFSHelper(i.dest,visited,recst);
}
recst.push(index);
}
ArrayList<ArrayList<Integer>> stronglyConnectedComponentsKosaraju(){
ArrayList<Integer>sortedbyendtime=topologicalSortingDFS();
ArrayList<ArrayList<Edge>>transposegraph=new ArrayList<>();
for(int i=0;i<vertex;i++){
transposegraph.add(new ArrayList<>());
}
for(int i=0;i<vertex;i++){
for(Edge j:graph.get(i)){
transposegraph.get(j.dest).add(new Edge(j.dest,j.src, j.weight));
}
}
ArrayList<ArrayList<Integer>>ans=new ArrayList<>();
boolean visited[]=new boolean[vertex];
for(int i:sortedbyendtime){
if(!visited[i]){
ArrayList<Integer>curr=DFSTopologicalSort(i,transposegraph,visited);
ans.add(curr);
}
}
return ans;
}
ArrayList<Integer> DFSTopologicalSort(int source,ArrayList<ArrayList<Edge>>graph,boolean visited[]){
ArrayList<Integer> ans=new ArrayList<>();
DFSTopologicalSortHelper(source,graph,visited,ans);
return ans;
}
void DFSTopologicalSortHelper(int source,ArrayList<ArrayList<Edge>>graph,boolean visited[],ArrayList<Integer> ans) {
visited[source]=true;
ans.add(source);
for(Edge i:graph.get(source)){
if(!visited[i.dest])
DFSTopologicalSortHelper(i.dest,graph,visited,ans);
}
}
long[] bellmanford(int source){
long ans[]=new long[vertex];
ans[source]=0;
for(int i=0;i<vertex-1;i++){//Considering paths of length 1 to paths of length (v-1) from source
for(int j=0;j<vertex;j++){
for(Edge k:graph.get(j)){
if(ans[k.dest]>ans[k.src]+ans[k.weight])
ans[k.dest]=ans[k.src]+ans[k.weight];
}
}
}
return ans;
}
}
class reader {
BufferedReader br;
StringTokenizer st;
public reader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextInt();
}
return array;
}
public long[] nextLongArray(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ec2ac690f14b2d3a03e90a3d350763d2
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class First {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
//int a = 1;
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
//out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
int n;
int[] arr;
long[][] dp = new long[5005][5005];
ArrayList<Integer> zero;
ArrayList<Integer> one;
int zeros, ones;
public void call(InputReader in, PrintWriter out) {
n = in.nextInt();
arr = new int[n];
one = new ArrayList<>();
zero = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if(arr[i]==0){
zero.add(i);
}
else{
one.add(i);
}
}
zeros = zero.size();
ones = one.size();
for (int i = 0; i <= ones+1; i++) {
for (int j = 0; j <= zeros+1; j++) {
dp[i][j] = -1;
}
}
out.println(ans(0,0));
}
public long ans(int ind, int ind1){
if(ind>= ones){
return 0;
}
if(ind1>= zeros){
return Integer.MAX_VALUE;
}
long opt;
if(dp[ind][ind1]!=-1) {
return dp[ind][ind1];
}
opt = (long)Math.abs(one.get(ind) - zero.get(ind1)) + ans(ind+1,ind1+1);
opt = Math.min(opt, ans(ind, ind1+1));
dp[ind][ind1] = opt;
return dp[ind][ind1];
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a;
int b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.a - this.a;
}
@Override
public boolean equals(Object o){
if(o instanceof answer){
answer c = (answer)o;
return a == c.a && b == c.b;
}
return false;
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer1 o) {
if(o.c==this.c){
return this.a - o.a;
}
return o.c - this.c;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (Long i:a) l.add(i);
l.sort(Collections.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
efb85d61dde780c59873c0e1f600e0e3
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
/**
* Created by Himanshu
**/
import java.util.*;
import java.io.*;
import java.math.*;
public class D1525 {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Reader s = new Reader();
int n = s.i();
int [] arr = s.arr(n);
ArrayList<Integer> ones = new ArrayList<>();
for (int i=0;i<n;i++) {
if (arr[i] == 1) ones.add(i);
}
int m = ones.size();
int [][] dp = new int[m+1][n+1];
for (int i=0;i<=m;i++) Arrays.fill(dp[i],Integer.MAX_VALUE);
dp[0][0] = 0;
for (int i=0;i<=m;i++) {
for (int j=0;j<n;j++) {
if (dp[i][j] == Integer.MAX_VALUE) continue;
dp[i][j+1] = Math.min(dp[i][j],dp[i][j+1]);
if (arr[j] == 0 && i != m) {
dp[i+1][j+1] = Math.min(dp[i+1][j+1],dp[i][j] + Math.abs(ones.get(i)-j));
}
}
}
out.println(dp[m][n]);
out.flush();
}
public static void shuffle(long[] arr) {
int n = arr.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
long temp = arr[i];
int randomPos = i + rand.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = temp;
}
}
private static int gcd(int a, int b) {
if(b == 0) return a;
return gcd(b,a%b);
}
public static long nCr(long[] fact, long[] inv, int n, int r, long mod) {
if (n < r)
return 0;
return ((fact[n] * inv[n - r]) % mod * inv[r]) % mod;
}
private static void factorials(long[] fact, long[] inv, long mod, int n) {
fact[0] = 1;
inv[0] = 1;
for (int i = 1; i <= n; ++i) {
fact[i] = (fact[i - 1] * i) % mod;
inv[i] = power(fact[i], mod - 2, mod);
}
}
private static long power(long a, long n, long p) {
long result = 1;
while (n > 0) {
if (n % 2 == 0) {
a = (a * a) % p;
n /= 2;
} else {
result = (result * a) % p;
n--;
}
}
return result;
}
private static long power(long a, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 0) {
a = (a * a);
n /= 2;
} else {
result = (result * a);
n--;
}
}
return result;
}
private static long query(long[] tree, int in, int start, int end, int l, int r) {
if (start >= l && r >= end) return tree[in];
if (end < l || start > r) return 0;
int mid = (start + end) / 2;
long x = query(tree, 2 * in, start, mid, l, r);
long y = query(tree, 2 * in + 1, mid + 1, end, l, r);
return x + y;
}
private static void update(int[] arr, long[] tree, int in, int start, int end, int idx, int val) {
if (start == end) {
tree[in] = val;
arr[idx] = val;
return;
}
int mid = (start + end) / 2;
if (idx > mid) update(arr, tree, 2 * in + 1, mid + 1, end, idx, val);
else update(arr, tree, 2 * in, start, mid, idx, val);
tree[in] = tree[2 * in] + tree[2 * in + 1];
}
private static void build(int[] arr, long[] tree, int in, int start, int end) {
if (start == end) {
tree[in] = arr[start];
return;
}
int mid = (start + end) / 2;
build(arr, tree, 2 * in, start, mid);
build(arr, tree, 2 * in + 1, mid + 1, end);
tree[in] = (tree[2 * in + 1] + tree[2 * in]);
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String s() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long l() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int i() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public double d() throws IOException {
return Double.parseDouble(s());
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int[] arr(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = i();
}
return ret;
}
public long[] arrLong(int n) {
long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = l();
}
return ret;
}
}
// static class pairLong implements Comparator<pairLong> {
// long first, second;
//
// pairLong() {
// }
//
// pairLong(long first, long second) {
// this.first = first;
// this.second = second;
// }
//
// @Override
// public int compare(pairLong p1, pairLong p2) {
// if (p1.first == p2.first) {
// if(p1.second > p2.second) return 1;
// else return -1;
// }
// if(p1.first > p2.first) return 1;
// else return -1;
// }
// }
// static class pair implements Comparator<pair> {
// int first, second;
//
// pair() {
// }
//
// pair(int first, int second) {
// this.first = first;
// this.second = second;
// }
//
// @Override
// public int compare(pair p1, pair p2) {
// if (p1.first == p2.first) return p1.second - p2.second;
// return p1.first - p2.first;
// }
// }
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
f4bc75d2656bd4dfe737faed51a4e4e9
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
/*input
5
0 0 0 0 0
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static int MOD = 1000000007;
static FastReader scan;
/*-------- I/O usaing short named function ---------*/
public static String ns(){return scan.next();}
public static int ni(){return scan.nextInt();}
public static long nl(){return scan.nextLong();}
public static double nd(){return scan.nextDouble();}
public static String nln(){return scan.nextLine();}
public static void p(Object o){out.print(o);}
public static void ps(Object o){out.print(o + " ");}
public static void pn(Object o){out.println(o);}
/*-------- for output of an array ---------------------*/
static void iPA(int arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void lPA(long arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void sPA(String arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
static void dPA(double arr []){
StringBuilder output = new StringBuilder();
for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output);
}
/*-------------- for input in an array ---------------------*/
static void iIA(int arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ni();
}
static void lIA(long arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nl();
}
static void sIA(String arr[]){
for(int i=0; i<arr.length; i++)arr[i] = ns();
}
static void dIA(double arr[]){
for(int i=0; i<arr.length; i++)arr[i] = nd();
}
/*------------ for taking input faster ----------------*/
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
// Method to check if x is power of 2
static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0);}
//Method to return lcm of two numbers
static int gcd(int a, int b){return a==0?b:gcd(b % a, a); }
//Method to count digit of a number
static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);}
//Method for sorting
static void ruffle_sort(int[] a) {
//shandom_ruffle
Random r=new Random();
int n=a.length;
for (int i=0; i<n; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//sort
Arrays.sort(a);
}
//Method for checking if a number is prime or not
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
out =new PrintWriter(outputStream);
scan =new FastReader();
//for fast output sometimes
StringBuilder sb = new StringBuilder();
int t = 1;
while(t-->0){
int n = ni();
int arr[] = new int[n];
iIA(arr);
ArrayList<Integer> zero = new ArrayList<>();
ArrayList<Integer> one = new ArrayList<>();
for(int i=0; i<n; i++){
if(arr[i] == 0) zero.add(i);
else one.add(i);
}
// ans = Math.min(solve(i, j-1), solve(i-1, j-1) + abs(j - i));
// base case : if(i==0) return 0
int z = zero.size(), o = one.size();
long dp[][] = new long[o+1][z+1];
for(int i=0; i<=o; i++){
for(int j=0; j<=z; j++){
if(i == 0){
dp[i][j] = 0;
continue;
}
else if(j == 0){
dp[i][j] = Integer.MAX_VALUE;
continue;
}
dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j-1] + Math.abs(zero.get(j-1) - one.get(i-1)));
}
}
pn(dp[o][z]);
}
out.flush();
out.close();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
0d1489f77da09935052806034879190b
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
// import java.lang.*;
import java.io.*;
// THIS TEMPLATE MADE BY AKSH BANSAL.
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static boolean[] isPrime;
private static void primes(){
int num = (int)1e6; // PRIMES FROM 1 TO NUM
isPrime = new boolean[num];
for (int i = 2; i< isPrime.length; i++) {
isPrime[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(isPrime[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
isPrime[j] = false;
}
}
}
}
private static long gcd(long a, long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static long pow(long x,long y){
if(y==0)return 1;
long temp = pow(x, y/2);
if(y%2==1){
return x*temp*temp;
}
else{
return temp*temp;
}
}
// static ArrayList<Integer>[] adj;
// static void getAdj(int n,int q, FastReader sc){
// adj = new ArrayList[n+1];
// for(int i=1;i<=n;i++){
// adj[i] = new ArrayList<>();
// }
// for(int i=0;i<q;i++){
// int a = sc.nextInt();
// int b = sc.nextInt();
// adj[a].add(b);
// adj[b].add(a);
// }
// }
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
// primes();
// ________________________________
// int t = sc.nextInt();
// StringBuilder output = new StringBuilder();
// while (t-- > 0) {
// output.append(solver()).append("\n");
// }
// out.println(output);
// _______________________________
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
out.println(solver(n, arr));
// ________________________________
out.flush();
}
public static long solver(int n, int[] arr) {
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for(int i=0;i<n;i++){
if(arr[i] ==1){
a.add(i);
}
else{
b.add(i);
}
}
// System.out.println("__"+ a);
// System.out.println("__"+ b);
long inf = (long)1e10;
int aLen = a.size(), bLen = b.size();
long[][] dp = new long[bLen+1][aLen+1];
for(int i=0;i<bLen+1;i++)Arrays.fill(dp[i],inf);
// dp[0][0] = 0;
for(int i=0;i<=bLen;i++){
dp[i][0] = 0;
}
for(int i=1;i<=bLen;i++){
for(int j=1;j<=i && j<=aLen;j++){
int aa = a.get(j-1);
int bb = b.get(i-1);
// System.out.println((i-1)+" "+(j-1)+"__"+ aa+" "+bb);
dp[i][j] = Math.min(
Math.abs(aa-bb)+dp[i-1][j-1],
dp[i-1][j]
);
// System.out.println((i-1)+" "+(j-1)+"__"+ dp[i][j]);
}
}
// for(int i=0;i<=bLen;i++){
// for(int j=0;j<=aLen;j++){
// System.out.print(dp[i][j]+" ");
// }
// System.out.println("__" );
// }
return dp[bLen][aLen]==inf?0:dp[bLen][aLen];
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
3febb07191f52888768378216dfde6b6
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.math.*;
import java.io.*;
public class A{
static FastReader scan=new FastReader();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static LinkedList<Integer>edges[];
// static LinkedList<Pair>edges[];
static boolean stdin = true;
static String filein = "input";
static String fileout = "output";
static int dx[] = { -1, 0, 1, 0 };
static int dy[] = { 0, 1, 0, -1 };
int dx_8[]={1,1,1,0,0,-1,-1,-1};
int dy_8[]={-1,0,1,-1,1,-1,0,1};
static char sts[]={'U','R','D','L'};
static boolean prime[];
static long LCM(long a,long b){
return (Math.abs(a*b))/gcd(a,b);
}
public static int upperBound(long[] array, int length, long value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = low+(high-low) / 2;
if ( array[mid]>value) {
high = mid ;
} else {
low = mid+1;
}
}
return low;
}
static long gcd(long a, long b) {
if(a!=0&&b!=0)
while((a%=b)!=0&&(b%=a)!=0);
return a^b;
}
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
if((n&1)!=1)
count++;
//count += n & 1;
n >>= 1;
}
return count;
}
static void sieve(long n)
{
prime = new boolean[(int)n+1];
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
}
static boolean isprime(long x)
{
for(long i=2;i*i<=x;i++)
if(x%i==0)
return false;
return true;
}
static int perm=0,FOR=0;
static boolean flag=false;
static int len=100000000;
static ArrayList<Pair>inters=new ArrayList<Pair>();
static class comp1 implements Comparator<Pair>{
public int compare(Pair o1,Pair o2){
return Integer.compare((int)o2.x,(int)o1.x);
}
}
public static class comp2 implements Comparator<Pair>{
public int compare(Pair o1,Pair o2){
return Integer.compare((int)o2.x,(int)o1.x);
}
}
static StringBuilder a,b;
static boolean isPowerOfTwo(int n)
{
if(n==0)
return false;
return (int)(Math.ceil((Math.log(n) / Math.log(2)))) ==
(int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static ArrayList<Integer>v;
static ArrayList<Integer>pows;
static void block(long x)
{
v = new ArrayList<Integer>();
pows=new ArrayList<Integer>();
while (x > 0)
{
v.add((int)x % 2);
x = x / 2;
}
// Displaying the output when
// the bit is '1' in binary
// equivalent of number.
for (int i = 0; i < v.size(); i++)
{
if (v.get(i)==1)
{
pows.add(i);
}
}
}
static long ceil(long a,long b)
{
if(a%b==0)
return a/b;
return a/b+1;
}
static int n,m;
static int arr[];
static long ans=0;
static boolean vis[]=new boolean[21];
static int c[]=new int[21];
static ArrayList<Integer>comps[];
static boolean isprime(int n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
// Function to return the smallest
// prime number greater than N
static int nextPrime(int N)
{
// Base case
if (N <= 1)
return 2;
int prime = N;
boolean found = false;
// Loop continuously until isPrime returns
// true for a number greater than n
while (!found)
{
prime++;
if (isprime(prime))
found = true;
}
return prime;
}
static long dp[][]=new long[3000][5001];
static long mod=(long)1e9+7;
static int mx=0,k;
static long nPr(long n,long r)
{
long ret=1;
for(long i=n-r+1;i<=n;i++)
{
ret=1L*ret*i%mod;
}
return ret%mod;
}
static Set<Long>set;
static TreeMap<Long,Integer>tmap;
static long pre[];
static ArrayList<Long>free;
static ArrayList<Long>notfree;
static long rec(int i,int j)
{
if(i>=notfree.size())
return 0;
if(j>=free.size())
return Integer.MAX_VALUE;
if(dp[i][j]!=-1)
return dp[i][j];
long ret=Integer.MAX_VALUE;
ret=Math.min(rec(i,j+1),rec(i+1,j+1)+(Math.abs(notfree.get(i)-free.get(j))));
//out.println(ret);
//out.println(ret);
return dp[i][j]=ret;
}
public static void main(String[] args) throws Exception
{
//SUCK IT UP AND DO IT ALRIGHT
//scan=new FastReader("hps.in");
//out = new PrintWriter("hps.out");
//System.out.println( 1005899102^431072812);
//int elem[]={1,2,3,4,5};
//System.out.println("avjsmlfpb".compareTo("avjsmbpfl"));
int tt=1;
/*for(int i=0;i<=100;i++)
if(prime[i])
arr.add(i);
System.out.println(arr.size());*/
// check(new StringBuilder("05:11"));
// System.out.println(26010000000000L%150);
//System.out.println((1000000L*99000L));
// tt=scan.nextInt();
// System.out.println(2^6^4);
//StringBuilder o=new StringBuilder("GBGBGG");
//o.insert(2,"L");
int T=tt;
//System.out.println(gcd(3,gcd(24,gcd(120,168))));
//System.out.println(gcd(40,gcd(5,5)));
//System.out.println(gcd(45,gcd(10,5)));
outer:while(tt-->0)
{
n=scan.nextInt();
arr=new int[n];
int pre[]=new int[n];
Arrays.fill(pre,1);
free=new ArrayList<Long>();
notfree=new ArrayList<Long>();
for(int i=0;i<n;i++){
arr[i]=scan.nextInt();
if(arr[i]==0)
free.add((long)i);
else notfree.add((long)i);
}
for(long K[]:dp)
Arrays.fill(K,-1);
out.println(rec(0,0));
}
out.close();
//SEE UP
}
static class special implements Comparable<special>{
int x,y,z,h;
String s;
special(int x,int y,int z,int h)
{
this.x=x;
this.y=y;
this.z=z;
this.h=h;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
special t = (special)o;
return t.x == x && t.y == y&&t.s.equals(s);
}
public int compareTo(special o)
{
return Integer.compare(x,o.x);
}
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastReader(String filename)throws Exception
{
br=new BufferedReader(new FileReader(filename));
}
boolean hasNext(){
String line;
while(root.hasMoreTokens())
return true;
return false;
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextInt();
}
return array;
}
}
static class Pair implements Comparable<Pair>{
public long x, y;
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y;
}
public int compareTo(Pair o)
{
return (int)(o.x-x);
}
}
static class tuple{
int x,y,z;
tuple(int a,int b,int c){
x=a;
y=b;
z=c;
}
}
static class Edge{
int d,w;
Edge(int d,int w)
{
this.d=d;
this.w=w;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
08619dd694ae5c2708e22f5446fdeb8e
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class CodeForces extends Functions {
/*
--> we have some index having 1 in it which are stored in ones.
--> we have some index having 0 on it which are stored in ones.
--> we need to select exactly one 0index for one 1index.
--> so in total we need exactly freq of 1 numbers element from 0. to find this optimally , we do dp
*/
static long[][] dp;
private static void solve() {
int n = sc.nextInt();
int[] arr = sc.setintArray(n);
List<Integer> ones = new ArrayList<>();
List<Integer> zeros = new ArrayList<>();
for(int i=0;i<n;i++)
if(arr[i]==0)zeros.add(i);
else ones.add(i);
dp = new long[ones.size()][zeros.size()];
for(int i=0;i<ones.size();i++)Arrays.fill(dp[i],-1);
out.println(helper(0,0,ones,zeros));
}
private static long helper(int i,int j,List<Integer> ones,List<Integer> zeros){
if(i==ones.size()) return 0;
if(j==zeros.size()) return INT_MAX;
if(dp[i][j]!=-1)return dp[i][j];
long c1 = Math.abs(zeros.get(j) - ones.get(i)) + helper(i+1,j+1,ones,zeros);
long c2 = helper(i,j+1,ones,zeros);
return dp[i][j] = Math.min(c1,c2);
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
int testCase = 1;
// testCase= sc.nextInt();
while (testCase-->0) solve();
long end = System.currentTimeMillis();
// out.println("time took in ms : "+(end-start));
sc.close();
out.flush();
out.close();
}
static Scanner sc = new Scanner(); // Input
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // output
}
class Functions {
public static long mod = (long)1e9+7L;
public static final int INT_MAX = Integer.MAX_VALUE;
public static final int INT_MIN = Integer.MIN_VALUE;
public static final long LONG_MAX = Long.MAX_VALUE;
public static final long LONG_MIN = Long.MIN_VALUE;
public static final double DOUBLE_MAX = Double.MAX_VALUE;
public static final double DOUBLE_MIN = Double.MIN_VALUE;
public static final String YES = "YES";
public static final String NO = "NO";
public static void sort(int[] a,boolean isAscending){
ArrayList<Integer> temp = new ArrayList<>();
for (int j : a) temp.add(j);
sort(temp,isAscending);
for(int i=0;i<a.length;i++)a[i] = temp.get(i);
}
public static void sort(List list,boolean isAscending){
if(isAscending)
Collections.sort(list);
else Collections.sort(list,Collections.reverseOrder());
}
// euclidean algorithm
public static long gcd(long a, long b) {
// time O(max (loga ,logb))
long x = Math.min(a,b);
long y = Math.max(a,b);
if (y % x == 0) return x;
return gcd(y%x,x);
}
public static long lcm(long a, long b) {
// lcm(a,b) * gcd(a,b) = a * b
return (a / gcd(a, b)) * b;
}
public static long factorial(long n){
long fact = 1L;
for(int i=2;i<=n;i++)fact = (fact*i)%mod;
return fact;
}
public static long firstDivisor(long n){
if(n==1)return n;
for(long i=2;i*i<=n;i++)
if(n%i==0)return i;
return -1;
}
public static long power(long x,long n){
// calculate x^n %mod using binary exponentiation
// time : O(logn)
long ans = 1;
while(n>0){
if(n%2!=0){
ans *= x;
n--;
}else {
x *= x;
n/=2;
}
x %=mod;
ans %=mod;
}
return ans;
}
public static int ncr(int n, int r){
// time O(n+r)
if (r > n)
return 0;
long[] inv = new long[r + 1];
inv[1] = 1;
// Getting the modular inversion
// for all the numbers
// from 2 to r with respect to m
for (int i = 2; i <= r; i++) {
inv[i] = mod - (mod / i) * inv[(int) (mod % i)] % mod;
}
int ans = 1;
// for 1/(r!) part
for (int i = 2; i <= r; i++) {
ans = (int) (((ans % mod) * (inv[i] % mod)) % mod);
}
// for (n)*(n-1)*(n-2)*...*(n-r+1) part
for (int i = n; i >= (n - r + 1); i--) {
ans = (int) (((ans % mod) * (i % mod)) % mod);
}
return ans;
}
public static void reverseArray(int[] a){
int left = 0;
int right = a.length-1;
while (left<right){
int temp =a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
}
}
}
class Scanner {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st = new StringTokenizer("");
public String next(){
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt(){return Integer.parseInt(next());}
public long nextLong(){return Long.parseLong(next());}
public double nextDouble(){return Double.parseDouble(next());}
public int[] setintArray(int n){
int[] arr =new int[n];
for(int i=0;i<n;i++)arr[i] = nextInt();
return arr;
}
public long[] setlongArray(int n){
long[] arr =new long[n];
for(int i=0;i<n;i++)arr[i] = nextLong();
return arr;
}
public int[][] set2DintArray(int row, int col){
int[][] arr = new int[row][col];
for(int i=0;i<row;i++)
for(int j= 0;j<col;j++)
arr[i][j] = nextInt();
return arr;
}
public long[][] set2DlongArray(int row, int col){
long[][] arr = new long[row][col];
for(int i=0;i<row;i++)
for(int j= 0;j<col;j++)
arr[i][j] = nextLong();
return arr;
}
public void close(){
try{
br.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
3b3d5fed3a81dd88e8e88296517d4079
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
int n=Integer.parseInt(bu.readLine());
String s[]=bu.readLine().split(" ");
ArrayList<Integer> z=new ArrayList<>(),o=new ArrayList<>();
long dp[][]=new long[n+1][n+1];
int i,j,a;
for(i=0;i<n;i++)
{
a=Integer.parseInt(s[i]);
if(a==0) z.add(i);
else o.add(i);
}
for(i=1;i<=o.size();i++)
{
long min=dp[i-1][i-1];
for(j=i;j<=z.size();j++)
{
dp[i][j]=min+Math.abs(z.get(j-1)-o.get(i-1));
min=Math.min(min,dp[i-1][j]);
}
}
long ans=Long.MAX_VALUE;
for(i=o.size();i<=z.size();i++)
ans=Math.min(ans,dp[o.size()][i]);
System.out.print(ans);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
f6d17a808ff74e93d06705c0aae7cb82
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
//package com.wissamfawaz;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 10000000;
static final int NINF = -100000;
static FastScanner sc;
static PrintWriter pw;
public static void main2(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
//int Q = sc.ni();
//for (int q = 0; q < Q; q++) {
int l = 1, r = 1_000_000;
while(l != r) {
int mid = (l + r + 1)/2;
pw.println(mid);
pw.flush();
String response = sc.nextLine();
if(response.equals("<")) {
r = mid-1;
} else {
l = mid;
}
}
pw.println("! " + l);
pw.flush();
//}
//pw.close();
}
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
//int Q = sc.ni();
//for (int q = 0; q < Q; q++) {
int n = sc.ni();
int[] arr = sc.intArray(n);
int nbZeros = 0;
int nbOnes = 0;
for(int i=0; i<n; i++) {
if(arr[i] == 0) {
nbZeros++;
} else {
nbOnes++;
}
}
if(nbZeros == n) {
pw.println(0);
} else {
int[] ones = new int[nbOnes];
int[] zeros = new int[nbZeros];
int idxZeros = 0;
int idxOnes = 0;
for(int i=0; i<n; i++) {
if(arr[i] == 0) {
zeros[idxZeros++] = i;
} else {
ones[idxOnes++] = i;
}
}
long[][] dp = new long[ones.length+1][zeros.length+1];
for(int i=0; i<dp.length; i++) {
dp[i][dp[0].length-1] = INF;
}
dp[dp.length-1][dp[0].length-1] = 0;
long current;
for(int i=dp.length-2; i>=0; i--) {
for(int j=dp[0].length-2; j>=0; j--) {
current = Math.abs(ones[i] - zeros[j]);
dp[i][j] = Math.min(current + dp[i+1][j+1], dp[i][j+1]);
}
}
pw.println(dp[0][0]);
}
//}
pw.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni();
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl();
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
b1e514b18446693bdb065f4cfa1e1e50
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class D {
// *** ++
// +=-==+ +++=-
// +-:---==+ *+=----=
// +-:------==+ ++=------==
// =-----------=++=========================
// +--:::::---:-----============-=======+++====
// +---:..:----::-===============-======+++++++++
// =---:...---:-===================---===++++++++++
// +----:...:-=======================--==+++++++++++
// +-:------====================++===---==++++===+++++
// +=-----======================+++++==---==+==-::=++**+
// +=-----================---=======++=========::.:-+*****
// +==::-====================--: --:-====++=+===:..-=+*****
// +=---=====================-... :=..:-=+++++++++===++*****
// +=---=====+=++++++++++++++++=-:::::-====+++++++++++++*****+
// +=======++++++++++++=+++++++============++++++=======+******
// +=====+++++++++++++++++++++++++==++++==++++++=:... . .+****
// ++====++++++++++++++++++++++++++++++++++++++++-. ..-+****
// +======++++++++++++++++++++++++++++++++===+====:. ..:=++++
// +===--=====+++++++++++++++++++++++++++=========-::....::-=++*
// ====--==========+++++++==+++===++++===========--:::....:=++*
// ====---===++++=====++++++==+++=======-::--===-:. ....:-+++
// ==--=--====++++++++==+++++++++++======--::::...::::::-=+++
// ===----===++++++++++++++++++++============--=-==----==+++
// =--------====++++++++++++++++=====================+++++++
// =---------=======++++++++====+++=================++++++++
// -----------========+++++++++++++++=================+++++++
// =----------==========++++++++++=====================++++++++
// =====------==============+++++++===================+++==+++++
// =======------==========================================++++++
// created by : Nitesh Gupta
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] scn = (br.readLine()).trim().split(" ");
int n = Integer.parseInt(scn[0]);
long[] arr = new long[n];
boolean[] vis = new boolean[n];
scn = (br.readLine()).trim().split(" ");
zeros = new ArrayList<>();
ones = new ArrayList<>();
long[][] dp = new long[n + 2][n + 2];
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(scn[i]);
if (arr[i] == 1) {
vis[i] = true;
ones.add(i);
} else {
zeros.add(i);
}
}
int x = ones.size();
int y = zeros.size();
// source: https://math.stackexchange.com/questions/414182/finding-minimum-sum-of-absolute-differences-betweens-values-of-two-sets/536050
for (int i = 1; i <= x; i++) {
dp[i][y + 1] = (long) (1e15);
}
for (int i = x + 1; i <= n; i++) {
for (int j = 1; j <= n + 1; j++) {
dp[i][j] = 0;
}
}
dp[x + 1][y + 1] = 0;
// Base cases:
//
// dp[length of arr1][length of arr2] = 0
// dp[A][length of arr2] = infinity (it's impossible to pair the remaining elements of arr1).
//
for (int i = x; i > 0; i--) {
for (int j = y; j > 0; j--) {
dp[i][j] = dp[i][j + 1];
if (i <= x && j <= y) {
long curr = Math.abs(ones.get(i - 1) - zeros.get(j - 1));
dp[i][j] = Math.min(curr + dp[i + 1][j + 1], dp[i][j]);
}
}
}
sb.append(dp[1][1]);
sb.append("\n");
System.out.println(sb);
return;
}
static ArrayList<Integer> zeros;
static ArrayList<Integer> ones;
static long res;
public static void rec(int i, int n, int m, boolean[] vis, long[][] dp) {
}
public static void sort(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
long temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = (int) Math.random() * n;
int temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
public static void print(long[][] dp) {
for (long[] a : dp) {
for (long ele : a) {
System.out.print(ele + " ");
}
System.out.println();
}
}
public static void print(int[][] dp) {
for (int[] a : dp) {
for (int ele : a) {
System.out.print(ele + " ");
}
System.out.println();
}
}
public static void print(boolean[] dp) {
for (boolean ele : dp) {
System.out.print(ele + " ");
}
System.out.println();
}
public static void print(long[] dp) {
for (long ele : dp) {
System.out.print(ele + " ");
}
System.out.println();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
e10ffe6d32cef74d79e4c66ee6555e16
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DArmchairs solver = new DArmchairs();
solver.solve(1, in, out);
out.close();
}
static class DArmchairs {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if (a[i] == 1) {
list1.add(i);
} else {
list2.add(i);
}
}
int[][] dp = new int[list1.size() + 1][list2.size() + 1];
int inf = (int) 1e8;
for (int i = 1; i < dp.length; i++) {
Arrays.fill(dp[i], inf);
}
for (int i = 1; i <= list1.size(); i++) {
int p1 = list1.get(i - 1);
for (int j = i; j <= list2.size(); j++) {
int p2 = list2.get(j - 1);
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(p1 - p2));
}
}
out.println(dp[list1.size()][list2.size()]);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
3f69a9f4a090902828080178cbb1e8da
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DArmchairs solver = new DArmchairs();
solver.solve(1, in, out);
out.close();
}
static class DArmchairs {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if (a[i] == 1) {
list.add(i);
}
}
int[][] dp = new int[list.size() + 1][n + 1];
int inf = (int) 1e8;
for (int i = 1; i < dp.length; i++) {
Arrays.fill(dp[i], inf);
}
for (int i = 1; i <= list.size(); i++) {
int cur = list.get(i - 1);
for (int j = 1; j <= n; j++) {
if (a[j - 1] == 0) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(cur + 1 - j));
} else {
dp[i][j] = dp[i][j - 1];
}
}
}
out.println(dp[list.size()][n]);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
42ff15d0afc46694a45219d66b6f4c95
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class App {
public String getGreeting() {
return "Hello World!";
}
static int []a;
static ArrayList<Integer> f;
static int n;
static int m;
static long [][]dp;
static long solve(int pos,int j){
if(pos<0){
if(j<0){
return 0;
}
else return Integer.MAX_VALUE;
}
else if(j<0){
return 0;
}
else if(dp[pos][j]!=-1) return dp[pos][j];
long ans=Integer.MAX_VALUE;
if(a[pos]==1) ans=solve(pos-1,j);
else if(a[pos]==0){
int cost=Math.abs(f.get(j)-pos);
ans=Math.min(solve(pos-1,j-1)+cost,solve(pos-1, j));
}
return dp[pos][j]=ans;
}
public static void main(String[] args) {
FastScanner fs=new FastScanner();
n=fs.nextInt();
a=fs.readArray(n);
f=new ArrayList<Integer>();
for(int i=0;i<n;i++) if(a[i]==1)f.add(i);
m=f.size();
dp=new long[n+1][m+1];
for(int i=0;i<n;i++)for(int j=0;j<m;j++)dp[i][j]=-1;
long ans=solve(n-1,m-1);
System.out.println(ans);
}
static final long mod=1_000_000_007;
static long mul(long a, long b) {
return a*b%mod;
}
static long add(long a, long b) {
return (a+b)%mod;
}
static long fastPow(long base, long e) {
if (e==0) return 1;
long half=fastPow(base, e/2);
if (e%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static long[] facts, invFacts;
static void precomp() {
facts=new long[1_100_000];
invFacts=new long[1_100_000];
facts[0]=invFacts[0]=1;
for (int i=1; i<facts.length; i++) {
facts[i]=mul(i, facts[i-1]);
}
invFacts[invFacts.length-1]=fastPow(facts[facts.length-1], mod-2);
for (int i=invFacts.length-2; i>=0; i--) {
invFacts[i]=mul(invFacts[i+1], i+1);
}
if (mul(facts[6], invFacts[6])!=1) throw null;
}
static long nCk(int n, int k) {
return mul(facts[n], mul(invFacts[k], invFacts[n-k]));
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sortLong(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n){
long[]a =new long[n];
for(int i=0;i<n;i++){
a[i]=nextLong();
}
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7f9426b23d7bc43a8f1d0f42955809c1
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class D {
static int n;
static int[] arr;
public static void main(String[] args) throws IOException{
FastIO file = new FastIO();
n = file.nextInt();
arr = new int[n];
for (int i=0; i<n; i++){
arr[i] = file.nextInt();
}
ArrayList<Integer> ones = new ArrayList<>();
for (int i=0; i<n; i++){
if (arr[i] == 1) ones.add(i);
}
int m = ones.size();
if (m == 0){
file.println(0);
file.close();
return;
}
int[][] dp = new int[n][m+1];
for (int i=0; i<n; i++){
for (int j=1; j<=m; j++){
dp[i][j] = (int)1e9;
}
}
if (arr[0] == 0){
dp[0][1] = Math.abs(ones.get(0));
}
for (int i=1; i<n; i++){
for (int j=1; j<=m; j++){
dp[i][j] = dp[i-1][j];
if (arr[i] == 0){
dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1] + Math.abs(ones.get(j-1) - i));
}
}
}
file.println(dp[n-1][m]);
file.close();
}
static class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
public FastIO(String i) throws IOException {
super(System.out);
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
0b4c1ef6edac40c5d44a5ce960d237da
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
-> Give your 100%, that's it!
-> Rules To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
static int[][] dp = new int[2501][5001];
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int yo = 1;
while (yo-- > 0) {
int n = sc.nextInt();
int[] a = sc.readInts(n);
List<Integer> l1 = new ArrayList<>();
List<Integer> l2 = new ArrayList<>();
for(int i = 0; i < n; i++){
if(a[i] == 1){
l1.add(i);
}
else {
l2.add(i);
}
}
for(int[] e : dp) Arrays.fill(e,-1);
out.println(helper(n,a,l1,l2,0,0));
}
out.close();
}
static int helper(int n, int[] a, List<Integer> l1, List<Integer> l2, int i, int j){
if(i >= l1.size()){
return 0;
}
if(j >= l2.size()){
return Integer.MAX_VALUE-10000;
}
if(dp[i][j] != -1) return dp[i][j];
int op1 = abs(l1.get(i)-l2.get(j)) + helper(n,a,l1,l2,i+1,j+1);
int op2 = helper(n,a,l1,l2,i,j+1);
return dp[i][j] = min(op1,op2);
}
/*
Source: hu_tao
Random stuff to try when stuck:
- use bruteforcer
- always check for n = 1, n = 2, so on
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr, PrintWriter out) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
public static int log2(int a){
return (int)(Math.log(a)/Math.log(2));
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
29eb44657929ebf4574eb2c24078ea50
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class Solution
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static final long mod=(long)1e9+7;
public static long pow(long a,int p)
{
long res=1;
while(p>0)
{
if(p%2==1)
{
p--;
res*=a;
res%=mod;
}
else
{
a*=a;
a%=mod;
p/=2;
}
}
return res;
}
static class Pair
{
int u,v,w;
Pair(int u,int v,int w)
{
this.u=u;
this.v=v;
this.w=w;
}
}
/*static class Pair implements Comparable<Pair>
{
int v,l;
Pair(int v,int l)
{
this.v=v;
this.l=l;
}
public int compareTo(Pair p)
{
return l-p.l;
}
}*/
static int gcd(int a,int b)
{
if(b%a==0)
return a;
return gcd(b%a,a);
}
public static void dfs(int u,int dist[],int sub[],int mxv[],int par[],ArrayList<Integer> edge[])
{
sub[u]=1;
for(int v:edge[u])
{
if(dist[v]==-1)
{
par[v]=u;
dist[v]=dist[u]+1;
dfs(v,dist,sub,mxv,par,edge);
if(sub[v]+1>sub[u])
{
sub[u]=sub[v]+1;
mxv[u]=v;
}
}
}
}
public static void main(String args[])throws Exception
{
FastReader fs=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
//int tc=fs.nextInt();
int n=fs.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=fs.nextInt();
ArrayList<Integer> o=new ArrayList<>();
ArrayList<Integer> z=new ArrayList<>();
for(int i=0;i<n;i++)
{
if(a[i]==1)o.add(i);
else z.add(i);
}
int ans[][]=new int[o.size()+1][z.size()+1];
for(int i=1;i<=o.size();i++)
{
for(int j=i;j<=z.size();j++)
{
if(i==j)ans[i][j]=ans[i-1][j-1]+(int)Math.abs(o.get(i-1)-z.get(j-1));
else
ans[i][j]=Math.min(ans[i][j-1],ans[i-1][j-1]+(int)Math.abs(o.get(i-1)-z.get(j-1)));
}
}
pw.println(ans[o.size()][z.size()]);
pw.flush();
pw.close();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
9d091bb42c9f520d783b5aac277ea144
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int ar[] = new int[n];
for(int i = 0; i < n; i++){
ar[i] = Integer.parseInt(st.nextToken());
}
ArrayList<Integer> ones = new ArrayList<Integer>();
ArrayList<Integer> zeroes = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
if(ar[i] == 1)
ones.add(i);
else
zeroes.add(i);
}
int r = ones.size();
int c = zeroes.size();
int time[][] = new int[r][c];
System.out.println(calculateTime(time, r, c, 0, 0, ones, zeroes));
}
public static int calculateTime(int time[][], int r, int c, int currR, int currC, ArrayList<Integer> ones, ArrayList<Integer> zeroes){
// System.out.println(currR + " " + currC);
if(currR == r)
return 0;
if(currC == c)
return (int)1e9;
if(time[currR][currC] != 0)
return time[currR][currC];
return time[currR][currC] = Math.min((calculateTime(time, r, c, currR + 1, currC + 1, ones, zeroes) + Math.abs(ones.get(currR) - zeroes.get(currC))), calculateTime(time, r, c, currR, currC + 1, ones, zeroes));
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
17b66fc80de588aaffdd63af626dafd7
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class Main {
static int[] a=new int[5010];
static int[] b=new int[5010];
static int[][] f=new int[5010][5010];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int l=1,r=1;
for(int i=1;i<=n;i++)
{
int x=sc.nextInt();
if(x==1) a[l++]=i;
else b[r++]=i;
}
for(int i=0;i<=n;i++) Arrays.fill(f[i], 0x3f3f3f3f);
for(int i=0;i<=r;i++) f[0][i]=0;
for(int i=1;i<=l;i++)
for(int j=1;j<=r;j++)
{
f[i][j]=Math.min(f[i][j-1], f[i-1][j-1]+Math.abs(a[i]-b[j]));
}
System.out.println(f[l][r]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
9fa632a1c78372f2d807a1587be50152
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codeforces {
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
FastReader sc=new FastReader();
int n=sc.nextInt();
int a[]=new int[n];
ArrayList<Integer> arr0=new ArrayList<>();
ArrayList<Integer> arr1=new ArrayList<>();
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]==0)
arr0.add(i);
else
arr1.add(i);
}
n=arr0.size();
int m=arr1.size();
int dp[][]=new int[m+1][n+1];
for(int i=0;i<=n;i++)
{
dp[0][i]=0;
}
for(int i=1;i<=m;i++)
{
dp[i][i]=dp[i-1][i-1]+Math.abs(arr0.get(i-1)-arr1.get(i-1));
for(int j=i+1;j<=n;j++)
{
dp[i][j]=Math.min(dp[i-1][j-1]+Math.abs(arr0.get(j-1)-arr1.get(i-1)),dp[i][j-1]);
}
}
System.out.println(dp[m][n]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
6fe326c2ced852356a2244a529433561
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class b1 {
public static final int inf = 100000000;
public static void main(String[] args){
FastReader scan = new FastReader();
int n = scan.nextInt();
int[] a = new int[n];
Vector<Vector<Integer> > v = new Vector<Vector<Integer> >();
for(int i=0;i<2;i++) v.add(new Vector<Integer>());
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
v.get(a[i]).add(i);
}
int[][] dp = new int[2][n+1];
for(int i=0;i<2;i++) for(int j=0;j<=n;j++) dp[i][j] = inf;
dp[0][0] = 0;
for(int i=1;i<=v.get(0).size();i++){
int l0 = v.get(0).get(i-1);
for(int j=0;j<=n;j++){
dp[1][j] = dp[0][j];
}
for(int j=1;j<=i && j <= v.get(1).size();j++){
dp[1][j] = Math.min(dp[1][j], dp[0][j-1] + Math.abs(l0 - v.get(1).get(j-1)));
}
for(int j=0;j<=n;j++){
dp[0][j] = dp[1][j];
dp[1][j] = inf;
}
}
int m = v.get(1).size();
System.out.println(dp[0][m]);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
94fa82af259d56d03c6b789f301efbdc
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class b1 {
public static final int inf = 100000000;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] a = new int[n];
Vector<Vector<Integer> > v = new Vector<Vector<Integer> >();
for(int i=0;i<2;i++) v.add(new Vector<Integer>());
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
v.get(a[i]).add(i);
}
int[][] dp = new int[2][n+1];
for(int i=0;i<2;i++) for(int j=0;j<=n;j++) dp[i][j] = inf;
dp[0][0] = 0;
for(int i=1;i<=v.get(0).size();i++){
int l0 = v.get(0).get(i-1);
for(int j=0;j<=n;j++){
dp[1][j] = dp[0][j];
}
for(int j=1;j<=i && j <= v.get(1).size();j++){
dp[1][j] = Math.min(dp[1][j], dp[0][j-1] + Math.abs(l0 - v.get(1).get(j-1)));
}
for(int j=0;j<=n;j++){
dp[0][j] = dp[1][j];
dp[1][j] = inf;
}
}
int m = v.get(1).size();
System.out.println(dp[0][m]);
scan.close();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
5e468332de77a43263095933873bad90
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class D implements Runnable {
List<Integer> seats = new ArrayList<>(), empty = new ArrayList<>();
long[][] dp;
void solve() throws IOException {
int n = ri();
dp = new long[n + 1][n + 1];
for (int i = 0; i < n; i++) {
int a = ri();
if (a == 1)
seats.add(i + 1);
else
empty.add(i + 1);
}
find(0, 0);
print(dp[0][0]);
}
long find(int a, int b) {
if (a == seats.size())
return 0;
if ((seats.size() - a) > (empty.size() - b) || b == empty.size()) {
return dmax;
}
if (dp[a][b] != 0)
return dp[a][b];
dp[a][b] = min(find(a, b + 1), Math.abs(seats.get(a) - empty.get(b)) + find(a + 1, b + 1));
return dp[a][b];
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new D(), "1").start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
@Override
public void run() {
try {
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
in = System.in;
}
public int scan() throws IOException {
if (total < 0)
throw new InputMismatchException();
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public int intNext() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
return neg * integer;
}
public double doubleNext() throws IOException {
double doub = 0;
int n = scan();
while (isWhiteSpace(n))
n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else
throw new InputMismatchException();
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String read() throws IOException {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n))
n = scan();
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
}
static void shuffle(int[] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i];
aa[i] = aa[j];
aa[j] = tmp;
}
}
static void shuffle(int[][] aa) {
int n = aa.length;
Random rand = new Random();
for (int i = 1; i < n; i++) {
int j = rand.nextInt(i + 1);
int first = aa[i][0];
int second = aa[i][1];
aa[i][0] = aa[j][0];
aa[i][1] = aa[j][1];
aa[j][0] = first;
aa[j][1] = second;
}
}
// Gives strict lowerBound that previous number would be smaller than the target
int lowerBound(int[] arr, int val) {
int l = 0, r = arr.length - 1;
while (l < r) {
int mid = (r + l) >> 1;
if (arr[mid] >= val) {
r = mid;
} else
l = mid + 1;
}
return l;
}
// Gives strict upperBound that next number would be greater than the target
int upperBound(int[] arr, int val) {
int l = 0, r = arr.length - 1;
while (l < r) {
int mid = (r + l + 1) >> 1;
if (arr[mid] <= val) {
l = mid;
} else
r = mid - 1;
}
return l;
}
static void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() throws IOException {
return read.intNext();
}
static long rl() throws IOException {
return Long.parseLong(read.read());
}
static String rs() throws IOException {
return read.read();
}
static char rc() throws IOException {
return rs().charAt(0);
}
static double rd() throws IOException {
return read.doubleNext();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
8aea25fb6657c3f48dd506c7a151090e
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class chair{
static int INF = 10000000;
static ArrayList<Integer> ar = new ArrayList<Integer>();
static ArrayList<Integer> aar = new ArrayList<Integer>();
static int[][] dp = new int[5005][5005];
static int helper(int i ,int j,int n,int m){
if(i>=n){
return 0;
}
if(j>=m){
return INF;
}
if(dp[i][j]!=-1){
return dp[i][j];
}
int ans = Math.min(Math.abs(ar.get(i)-aar.get(j))+helper(i+1,j+1,n,m),helper(i,j+1,n,m));
dp[i][j] = ans;
return ans;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ar.clear();
aar.clear();
for(int i =0;i<5005;i++){
Arrays.fill(dp[i],-1);
}
int count = 0;
for(int i =0;i<n;i++){
int a = sc.nextInt();
if(a==1){
ar.add(i);
count++;
}
else{
aar.add(i);
}
}
if(count==0){
System.out.println(0);
}
else{
// System.out.println(ar.size());
// System.out.println(aar.size());
System.out.println(helper(0,0,ar.size(),aar.size()));
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ca3d817bb5485a2e8723a7b390bbe4b9
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class ArmChairs {
public static int solution(int n, int[] arr) {
ArrayList<Integer> one = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
one.add(i);
} else {
zero.add(i);
}
}
int[][] dp = new int[one.size() + 1][zero.size() + 1];
for (int i = 1; i <= one.size(); i++) {
dp[i][i] = dp[i - 1][i - 1] + Math.abs(one.get(i - 1) - zero.get(i - 1));
for (int j = i + 1; j <= zero.size(); j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(one.get(i - 1) - zero.get(j - 1)));
}
}
return dp[one.size()][zero.size()];
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s[i]);
}
log.write(Integer.toString(solution(n, arr)) + "\n");
log.flush();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ea5aba233b765a5bafa2bcf62e71eb14
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class Main {
static int[] a=new int[5010];
static int[] b=new int[5010];
static int[][] f=new int[5010][5010];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int l=1,r=1;
for(int i=1;i<=n;i++)
{
int x=sc.nextInt();
if(x==1) a[l++]=i;
else b[r++]=i;
}
for(int i=0;i<=n;i++) Arrays.fill(f[i], 0x3f3f3f3f);
for(int i=0;i<=r;i++) f[0][i]=0;
for(int i=1;i<=l;i++)
for(int j=1;j<=r;j++)
{
f[i][j]=Math.min(f[i][j-1], f[i-1][j-1]+Math.abs(a[i]-b[j]));
}
System.out.println(f[l][r]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ba46f584431064e7f14311d8ee5c9f45
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int[] pre = new int[n + 1];
List<Integer> z = new ArrayList<>();
List<Integer> o = new ArrayList<>();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
cnt++;
z.add(i);
}else{
o.add(i);
}
}
int[][] dp = new int[cnt + 1][(n - cnt) + 1];
int one = n - cnt;
Arrays.fill(dp[0], 100000000);
dp[0][0] = 0;
// System.out.println(one);
int min = 100000000;
for (int i = 1; i <= cnt; i++) {// the position of zero,
Arrays.fill(dp[i], 100000000);
dp[i][0] = 0;
for (int j = 1; j <= Math.min(one, i); j++) {// the position of one
if (cnt - i < one - j){
dp[i][j] = 100000000;
}else{
dp[i][j] = Math.min(dp[i - 1][j - 1] + Math.abs(o.get(j - 1) - z.get(i - 1)), dp[i - 1][j]);
}
if (j == one){
min = Math.min(min, dp[i][j]);
}
}
}
min = Math.min(min, dp[0][n - cnt]);
out.println(min);
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n) break;
ret[pos++] = p;
if ((long) p * p > n) continue;
for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
// reverse division for 2
public static long[] rdiv2(int n, int mod){
long[] arr = new long[n + 5];
arr[0] = 1;
long rev2 = (mod + 1) / 2;
for (int i = 1; i < n; i++) {
arr[i] = arr[i - 1] * rev2 % mod;
}
return arr;
}
static List<Integer> primeFactors(int n)
{
// Print the number of 2s that divide n
List<Integer> ls = new ArrayList<>();
if (n % 2 == 0) ls.add(2);
while (n%2==0)
{
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if (n % i == 0) ls.add(i);
while (n%i == 0)
{
n /= i;
}
}
if (n > 1) ls.add(n);
return ls;
}
static int find(int i, int[] par){
if (par[i] < 0) return i;
return par[i] = find(par[i], par);
}
static boolean union(int i, int j, int[] par){
int pi = find(i, par);
int pj = find(j, par);
if (pi == pj) return false;
if (par[pi] < par[pj]){
par[pi] += par[pj];
par[pj] = pi;
}else{
par[pj] += par[pi];
par[pi] = pj;
}
return true;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ffe5311b79ca8220186f793b18286256
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
/*
Author: Aman Patel
Date: 16-05-2021
*/
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Ed109 {
static int N = 5000;
static long[][] dp_arr = new long[N + 5][N + 5];
//static int _count = 0;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= N; j++) {
dp_arr[i][j] = -1;
}
}
int n;
n = fs.nextInt();
ArrayList<Integer> occupied = new ArrayList<>(), empty = new ArrayList<>();
int temp;
for (int i = 0; i < n; i++) {
temp = fs.nextInt();
if (temp == 1)
occupied.add(i);
else
empty.add(i);
}
int n1 = occupied.size(), n2 = empty.size();
long result = cost(occupied, empty, n1, n2, 0, 0);
out.println(result);
//out.println(_count);
out.close();
}
static long cost(ArrayList<Integer> occupied, ArrayList<Integer> empty, int n1, int n2, int i, int j) {
//_count++;
if (i == n1)
return 0;
else if (j == n2)
return (long) (1e15);
if (dp_arr[i][j] != -1)
return dp_arr[i][j];
long _min = Math.min(Math.abs(occupied.get(i) - empty.get(j)) + cost(occupied, empty, n1, n2, i + 1, j + 1), cost(occupied, empty, n1, n2, i, j + 1));
dp_arr[i][j] = _min;
return dp_arr[i][j];
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
}
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
6ea7af959ed50654701eb47b23a5961a
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
import java.util.stream.IntStream;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run(){
boolean tc = false;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start : while (testcases --> 0) {
int n = r.ni();
int[] arr = new int[n];
List<Integer> one = new ArrayList<>();
List<Integer> zero = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = r.ni();
if (arr[i] == 1) one.add(i);
else zero.add(i);
}
long[][] dp = new long[n + 2][n + 2];
for (int i = 1; i <= one.size(); i++)
dp[i][zero.size() + 1] = (long) (1e15);
dp[one.size() + 1][zero.size() + 1] = 0;
for (int i = one.size(); i > 0; i--) {
for (int j = zero.size(); j > 0; j--) {
if (i <= one.size() && j <= zero.size())
dp[i][j] = Math.min(Math.abs(one.get(i - 1) - zero.get(j - 1)) + dp[i + 1][j + 1], dp[i][j + 1]);
}
}
out.write((dp[1][1] + " ").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO{
final private int BUFFER_SIZE = 1<<16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do { ret = ret * 10 + c - '0'; }
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nl() throws IOException {
long ret = 0;byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do { ret = ret * 10 + c - '0'; }
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;return ret;
}
public double nd() throws IOException {
double ret = 0, div = 1;byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do { ret = ret * 10 + c - '0'; }
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {run();}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e>0) {
if ((e & 1)>0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); }
String word() {
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
String line() {
String str = "";
try { str = br.readLine(); }
catch (IOException e) { e.printStackTrace(); }
return str;
}
int ni() { return Integer.parseInt(word()); }
long nl() { return Long.parseLong(word()); }
double nd() { return Double.parseDouble(word()); }
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) { if (a == 0) return b;else return gcd(b % a, a); }
static long lcm(long a, long b) { return (a * b) / gcd(a, b); }
static long lower_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) < k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static int upper_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) <= k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1; return s;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
int first;int second;
public Pair(int first, int second) { this.first = first;this.second = second; }
public String toString() { return "(" + first + "," + second + ")"; }
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.first!=o.first)
return (int) (this.first - o.first);
else return(int)(this.second-o.second);
}
}
public static class PairC<X,Y> implements Comparable<PairC> {
X first;Y second;
public PairC(X first, Y second) { this.first = first;this.second = second; }
public String toString() { return "(" + first + "," + second + ")"; }
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
b83ea6932d6a2a46b774cb5fd6cb61b7
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class D {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
readInput();
out.close();
}
static List<Integer> o1, o0;
static int[][] dp;
static int solve(int i, int j) {
if (i >= dp.length) return 0;
if (j >= dp[0].length) return Integer.MAX_VALUE/10;
if (dp[i][j] == -1) {
dp[i][j] = Integer.min(solve(i,j+1), solve(i+1,j+1) + Math.abs(o1.get(i)-o0.get(j)));
}
return dp[i][j];
}
public static void readInput() throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
int n;
n = Integer.parseInt(br.readLine());
int[] a= new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
o1 = new ArrayList<Integer>();
o0 = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
if (a[i] == 1) o1.add(i);
else o0.add(i);
}
if (o1.size() == 0) {
out.println(0);
return;
}
dp = new int[o1.size()][o0.size()];
for (int[] x: dp) Arrays.fill(x, -1);
out.println(solve(0,0));
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
13012935babe450c1ae5e79a7512ab2c
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* @author is2ac
*/
public class D_CF {
public static boolean fail;
public static int id;
public static void main(String[] args) throws IOException {
FastScanner58 fs = new FastScanner58();
//Reader fs = new Reader();
PrintWriter pw = new PrintWriter(System.out);
//int t = fs.ni();
int t = 1;
for (int tc = 0; tc < t; tc++) {
int n = fs.ni();
int[] a = fs.intArray(n);
List<Integer> one = new ArrayList();
List<Integer> zero = new ArrayList();
for(int i = 0; i < n; i++) {
if (a[i]==0) {
zero.add(i);
} else {
one.add(i);
}
}
Integer[][] dp = new Integer[zero.size()+1][one.size()+1];
pw.println(recur(0,0,zero,one,dp));
}
pw.close();
}
public static int recur(int a, int b, List<Integer> zero, List<Integer> one, Integer[][] dp) {
int n = (int)(1e9);
if (b==one.size()) return 0;
if (a==zero.size()) return (int)(1e9);
if (dp[a][b]!=null) return dp[a][b];
n = Math.min(n,recur(a+1,b,zero,one,dp));
n = Math.min(n,recur(a+1,b+1,zero,one,dp)+Math.abs(zero.get(a)-one.get(b)));
return dp[a][b] = n;
}
public static long gcd(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return gcd(n2, n1 % n2);
}
}
class BIT16 {
int[] bit;
public BIT16(int size) {
bit = new int[size];
}
public void update(int ind, int delta) {
while (ind < bit.length) {
bit[ind] += delta;
ind = ind + (ind & (-1 * ind));
}
}
public int sum(int ind) {
int s = 0;
while (ind > 0) {
s += bit[ind];
ind = ind - (ind & (-1 * ind));
}
return s;
}
public int query(int l, int r) {
return sum(r) - sum(l);
}
}
class UnionFind18 {
int[] id;
public UnionFind18(int size) {
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i;
}
}
public int find(int p) {
int root = p;
while (root != id[root]) {
root = id[root];
}
while (p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
public void union(int p, int q) {
int a = find(p), b = find(q);
if (a == b) {
return;
}
id[b] = a;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) {
return;
}
din.close();
}
}
class FastScanner58 {
BufferedReader br;
StringTokenizer st;
public FastScanner58() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
ret[i] = ni();
}
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++) {
ret[i] = nl();
}
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
f3fe29f99bcad6f83502d5207d9f4d31
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class Armcharis {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
// int t = sc.nextInt();
int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
long INF = (long) 1e10;
public void solve(InputReader sc, PrintWriter out) {
int n = sc.nextInt();
int[] arr = sc.nextIntArray(n);
int cnt = 0;
for(int i : arr) if(i==1) cnt++;
if(cnt==0) {
out.println(0);
return;
}
int[] pos = new int[cnt];
int idx = 0;
for(int i = 0; i < n; i++) {
if(arr[i]==0) continue;
pos[idx++] = i;
}
long[][] dp = new long[cnt][n];
for(long[] ar : dp) Arrays.fill(ar,INF);
for(int i = 0; i < cnt; i++) {
int nowPos = pos[i];
for(int j = 0; j < n; j++) {
// if(arr[j]==1) continue;
long dist = Math.abs(nowPos-j);
if(arr[j]==1) dist = INF;
if(i==0) {
dp[i][j] = dist;
if(j>0) {
dp[i][j] = Math.min(dp[i][j],dp[i][j-1]);
}
continue;
}
if(j>0) {
dp[i][j] = dist + dp[i-1][j-1];
dp[i][j] = Math.min(dp[i][j],dp[i][j-1]);
}
}
}
long min = INF;
for(long l : dp[cnt-1]) min = Math.min(min,l);
out.println(min);
}
}
static void sort(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sortDec(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static void sortDec(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7bdf01cd092b8143ac9abbf2e1eb9f04
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class SeparateRough {
static Scanner scn = new Scanner(System.in);
public static void main(String args[]) {
int n = scn.nextInt();
int[] chair = new int[n];
for (int i = 0; i < chair.length; i++) {
chair[i] = scn.nextInt();
}
int[][] dp = new int[n + 1][n + 1];
for(int[]v:dp) {
Arrays.fill(v, -1);
}
int locc = 0; // last occupied
for (int i = 0; i < chair.length; i++) {
if (chair[i] == 1)
locc = i;
}
System.out.println(Armchairs(chair, 0, 0, locc, dp));
}
public static int Armchairs(int[] chair, int vidx, int occidx, int locc, int[][] dp) {
if (vidx == chair.length && occidx <= locc) {
return 10000000;
}
if (occidx > locc)
return 0;
if (dp[occidx][vidx] != -1) {
return dp[occidx][vidx];
}
int ans;
if (chair[occidx] == 0) {
ans = Armchairs(chair, vidx, occidx + 1, locc, dp);
dp[occidx][vidx] = ans;
return ans;
}
if (chair[vidx] == 0) {
int e = Math.abs(occidx - vidx);
ans = Math.min(e + Armchairs(chair, vidx + 1, occidx + 1, locc, dp),
Armchairs(chair, vidx + 1, occidx, locc, dp));
dp[occidx][vidx] = ans;
return ans;
} else {
ans = Armchairs(chair, vidx + 1, occidx, locc, dp);
dp[occidx][vidx] = ans;
return ans;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
44cc485c16c898bc4908af7bdb32f5c1
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.Arrays;
import java.util.Scanner;
public class P1525D {
public static int[] ones, zeros;
public static int[][] memo;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] arr = new int[n];
int oneCount = 0;
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
oneCount += arr[i] % 2;
}
int o = 0, z = 0;
ones = new int[oneCount];
zeros = new int[n - oneCount];
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 1) {
ones[o++] = i;
} else {
zeros[z++] = i;
}
}
memo = new int[oneCount][n - oneCount];
for (int[] row : memo) Arrays.fill(row, -1);
System.out.println(dp(0, 0));
}
public static int dp(int oi, int zi) {
if (oi == ones.length) {
return 0;
} else if (zi == zeros.length) {
return 100000000;
} else {
if (memo[oi][zi] == -1) {
memo[oi][zi] = Math.min(Math.abs(ones[oi] - zeros[zi]) + dp(oi + 1, zi + 1), dp(oi, zi + 1));
}
return memo[oi][zi];
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
9ab3423e07fdec39f323adac0ee83b49
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
// package com.company;
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
public static void main(String args[]){
InputReader in=new InputReader(System.in);
TASK solver = new TASK();
int t=1;
// t = in.nextInt();
for(int i=1;i<=t;i++)
{
solver.solve(in,i);
}
}
static class TASK {
static int mod = 1000000007;
static long solve(int a[],ArrayList<Integer> al,int i,int j,long dp[][])
{
if(j<0 || i<0)
return Integer.MAX_VALUE;
if(i==0 && j==0)
return 0;
if(j==0)
return 0;
if(i==0)
return Integer.MAX_VALUE;
if(dp[i-1][j-1]==-1)
{
dp[i-1][j-1]=solve(a,al,i-1,j-1,dp);
}
if(dp[i-1][j]==-1)
dp[i-1][j]=solve(a,al,i-1,j,dp);
if(a[i-1]==1)
return dp[i-1][j];
dp[i][j]=Math.min(dp[i-1][j],dp[i-1][j-1]+Math.abs(i-al.get(j-1)));
return dp[i][j];
}
void solve(InputReader in, int testNumber) {
int n = in.nextInt();
int a[] = new int[n+1];
long dp[][] = new long[n+1][n+1];
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<n;i++) {
a[i] = in.nextInt();
if(a[i]==1)
al.add(i+1);
Arrays.fill(dp[i],-1);
}
Arrays.fill(dp[n],-1);
System.out.println(solve(a,al,n,al.size(),dp));
}
}
static class pair{
int x ;
int y;
pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
static class Maths {
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c
== -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
243dd9023eb45ea9f159b9b75f97cfcb
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
public class A
{
static int size;
static int[] arr;
static char[] s;
public static void main(String[] args) throws IOException
{
f = new Flash();
out = new PrintWriter(System.out);
int T = 1; //ni();
for(int tc = 1; tc <= T; tc++){
size = ni(); arr = arr(size); sop(fn());
}
out.flush(); out.close();
}
static int fn()
{
List<Integer> o = new ArrayList<>(), z = new ArrayList<>();
for(int i = 0; i < size; i++) {
if(arr[i] == 1) o.add(i);
else z.add(i);
}
int n = o.size(), m = z.size();
if(n == 0) return 0;
int[][] dp = new int[n+1][m+1];
for(int i = 1; i <= n; i++) dp[i][0] = (int)mod;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
dp[i][j] = (int)mod;
int x = o.get(i-1), y = z.get(j-1);
dp[i][j] = min(dp[i][j], dp[i-1][j-1] + abs(x-y));
dp[i][j] = min(dp[i][j], dp[i][j-1]);
}
}
int ans = (int)mod;
for(int j = 0; j <= m; j++) ans = min(ans, dp[n][j]);
return ans;
}
static Flash f;
static PrintWriter out;
static final long mod = (long)1e9+7;
static final long inf = Long.MAX_VALUE;
static final int _inf = Integer.MAX_VALUE;
static final int maxN = (int)5e5+5;
static long[] fact, inv;
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void sort(long[] a){
List<Long> A = new ArrayList<>();
for(long i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void print(int[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static void print(long[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static int swap(int itself, int dummy){return itself;}
static long swap(long itself, long dummy){return itself;}
static void sop(Object o){out.println(o);}
static int ni(){return f.ni();}
static long nl(){return f.nl();}
static double nd(){return f.nd();}
static String next(){return f.next();}
static String ns(){return f.ns();}
static char[] nc(){return f.nc();}
static int[] arr(int len){return f.arr(len);}
static int gcd(int a, int b){if(b == 0) return a; return gcd(b, a%b);}
static long gcd(long a, long b){if(b == 0) return a; return gcd(b, a%b);}
static int lcm(int a, int b){return (a*b)/gcd(a, b);}
static long lcm(long a, long b){return (a*b)/gcd(a, b);}
static class Flash
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next(){
while(!st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String ns(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
char[] nc(){return ns().toCharArray();}
int ni(){return Integer.parseInt(next());}
long nl(){return Long.parseLong(next());}
double nd(){return Double.parseDouble(next());}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7a25c2b0360039c3110146529f5483a5
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.io.*;
import java.util.*;
public class A
{
static int n;
static int[] arr;
static char[] s;
public static void main(String[] args) throws IOException
{
f = new Flash();
out = new PrintWriter(System.out);
int T = 1; //ni();
for(int tc = 1; tc <= T; tc++){
n = ni(); arr = arr(n); sop(fn());
}
out.flush(); out.close();
}
static int fn()
{
List<Integer> o = new ArrayList<>(), z = new ArrayList<>();
for(int i = 0; i < n; i++) {
if(arr[i] == 1) o.add(i);
else z.add(i);
}
int n = o.size(), m = z.size();
int[][] dp = new int[n+1][m+1];
for(int i = 0; i <= n; i++) {
for(int j = 0; j <= m; j++) {
dp[i][j] = _inf/2;
}
}
for(int j = 0; j <= m; j++) dp[0][j] = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
int p = o.get(i-1), s = z.get(j-1);
dp[i][j] = dp[i-1][j-1] + abs(p-s);
dp[i][j] = min(dp[i][j], dp[i][j-1]);
}
}
return dp[n][m];
}
static Flash f;
static PrintWriter out;
static final long mod = (long)1e9+7;
static final long inf = Long.MAX_VALUE;
static final int _inf = Integer.MAX_VALUE;
static final int maxN = (int)5e5+5;
static long[] fact, inv;
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void sort(long[] a){
List<Long> A = new ArrayList<>();
for(long i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static void print(int[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static void print(long[] a){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < a.length; i++) sb.append(a[i] + " ");
sop(sb);
}
static int swap(int itself, int dummy){return itself;}
static long swap(long itself, long dummy){return itself;}
static void sop(Object o){out.println(o);}
static int ni(){return f.ni();}
static long nl(){return f.nl();}
static double nd(){return f.nd();}
static String next(){return f.next();}
static String ns(){return f.ns();}
static char[] nc(){return f.nc();}
static int[] arr(int len){return f.arr(len);}
static int gcd(int a, int b){if(b == 0) return a; return gcd(b, a%b);}
static long gcd(long a, long b){if(b == 0) return a; return gcd(b, a%b);}
static int lcm(int a, int b){return (a*b)/gcd(a, b);}
static long lcm(long a, long b){return (a*b)/gcd(a, b);}
static class Flash
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next(){
while(!st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String ns(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
char[] nc(){return ns().toCharArray();}
int ni(){return Integer.parseInt(next());}
long nl(){return Long.parseLong(next());}
double nd(){return Double.parseDouble(next());}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
6796e7641148b969543d73a7a32cf92b
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class Armchairs
{
public static int val(int b[],int m,int c[],int n,int dp[][])
{
if(dp[m][n]>-1)
{
return dp[m][n];
}
else
if(m==0)
{
return 0;
}
else
if(n==0)
{
return 2099999999;
}
else
{
return dp[m][n]=Math.min(val(b,m-1,c,n-1,dp)+Math.abs(b[m-1]-c[n-1]),val(b,m,c,n-1,dp));
}
}
public static void process()throws IOException
{
int n=I();
int a[]=Ai(n);
ArrayList<Integer> arr=new ArrayList<Integer>();
ArrayList<Integer> arr1=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
if(a[i]==0)
{
arr1.add(i);
}
else
{
arr.add(i);
}
}
int b[]=new int[arr.size()];
int c[]=new int[arr1.size()];
int m=arr.size();int n1=arr1.size();
int dp[][]=new int[m+1][n1+1];
dyn(dp,m+1,n1+1,-1);
for(int i=0;i<arr.size();i++)
{
b[i]=arr.get(i);
}
for(int i=0;i<arr1.size();i++)
{
c[i]=arr1.get(i);
}
arr.clear();
arr1.clear();
pn(val(b,m,c,n1,dp));
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static void pn(Object o){out.println(o);out.flush();}
static void p(Object o){out.print(o);out.flush();}
static void pni(Object o){out.println(o);System.out.flush();}
static int I() throws IOException{return sc.nextInt();}
static long L() throws IOException{return sc.nextLong();}
static double D() throws IOException{return sc.nextDouble();}
static String S() throws IOException{return sc.next();}
static char C() throws IOException{return sc.next().charAt(0);}
static int[] Ai(int n) throws IOException{int[] arr = new int[n];for (int i = 0; i < n; i++)arr[i] = I();return arr;}
static String[] As(int n) throws IOException{String s[] = new String[n];for (int i = 0; i < n; i++)s[i] = S();return s;}
static long[] Al(int n) throws IOException {long[] arr = new long[n];for (int i = 0; i < n; i++)arr[i] = L();return arr;}
static void dyn(int dp[][],int n,int m,int z)throws IOException {for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dp[i][j]=z;}} }
// *--------------------------------------------------------------------------------------------------------------------------------*//
static class AnotherReader {BufferedReader br;StringTokenizer st;AnotherReader() throws FileNotFoundException {br = new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(int a) throws FileNotFoundException {br = new BufferedReader(new FileReader("input.txt"));}
String next() throws IOException{while (st == null || !st.hasMoreElements()) {try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}}return st.nextToken();}
int nextInt() throws IOException {return Integer.parseInt(next());}
long nextLong() throws IOException {return Long.parseLong(next());}
double nextDouble() throws IOException {return Double.parseDouble(next());}
String nextLine() throws IOException {String str = "";try {str = br.readLine();} catch (IOException e) {e.printStackTrace();}return str;}}
public static void main(String[] args)throws IOException{try{boolean oj=true;if(oj==true)
{AnotherReader sk=new AnotherReader();PrintWriter out=new PrintWriter(System.out);}
else
{AnotherReader sk=new AnotherReader(100);out=new PrintWriter("output.txt");}
//long T=L();while(T-->0)
{process();}out.flush();out.close();}catch(Exception e){return;}}}
//*-----------------------------------------------------------------------------------------------------------------------------------*//
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
d0b0de212191bed12caf13d18ce79bd8
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import javax.sound.midi.SysexMessage;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class S2 {
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while(!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
private static void arrInp(int n1) throws IOException {
// TODO Auto-generated method stub
arr = new long[n1];
for(int i=0; i<n1; i++) {
long a = Reader.nextLong();
arr[i] = a;
}
}
static long[] merge(long[] a, long[] b) {
int m = a.length;
int n = b.length;
long [] c = new long[n+m];
int j=0, k=0;
while(j+k<m+n) {
if(j>=m) {
c[j+k] = b[k];
k++;
}
else if(k>=n) {
c[j+k] = a[j];
j++;
}
else {
if(a[j]<b[k]) {
c[j+k] = a[j];
j++;
}
else if(a[j]==b[k]) {
if(a[j]<b[k]) {
c[j+k] = a[j];
j++;
}
else {
c[j+k] = b[k];
k++;
}
}
else {
c[j+k] = b[k];
k++;
}
}
}
return c;
}
static long[] Msort(long[] unsorted){
int l = unsorted.length;
if(l<=1) {
return unsorted;
}
else {
long[] Msorted = new long[l];
long[] m1 = new long[l/2];
long[] m2 = new long[l-(l/2)];
for(int i=0; i<l; i++) {
if(i<l/2) {
m1[i] = unsorted[i];
}
else {
m2[i-(l/2)] = unsorted[i];
}
}
Msorted = merge(Msort(m1), Msort(m2));
return Msorted;
}
}
private static long inf = 1<<27;
private static long ans;
private static long n;
private static long k;
private static long[] arr;
private static char[] str;
private final static long qwerty = 1000000007;
private static boolean bruh;
private static class Node implements Comparable<Node> {
public int i;
public int v;
public char ch;
public Node(int ix, int x, char c) {
// TODO Auto-generated constructor stub
i=ix;
v=x;
ch=c;
}
@Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return this.v - o.v;
}
}
public static void main(String[] args) throws IOException {
ans = 0;
Reader.init(System.in);
OutputStream out = new BufferedOutputStream(System.out);
int tc=1;
// tc = Reader.nextInt();
main_loop:
for(int tn=0; tn<tc; tn++) {
ans=0;
bruh = false;
n=tn+1;
n = Reader.nextInt();
// k = Reader.nextInt();
int n1 = (int) n;
arrInp(n1);
int[] zero,one;
zero = new int[n1];
one = new int[n1];
int io=0;
int iz=0;
for(int i=0; i<n; i++) {
if(arr[i]==0) {
zero[iz++]=i+1;
}
else {
one[io++]=i+1;
}
}
int[][] dp = new int[iz+1][io+1];
for(int i=0; i<iz; i++) {
for(int j=0; j<io; j++) {
dp[i][j] = -1;
}
}
dp[iz][io] = 0;
ans = solve(dp, zero, one, iz, io, 0, 0);
// out.write(("YES").getBytes());
// out.write(("NO").getBytes());
out.write((ans+" ").getBytes());
out.write(("\n").getBytes());
}
out.flush();
out.close();
}
private static long solve(int[][] dp, int[] zero, int[] one, int iz, int io, int i, int j) {
// TODO Auto-generated method stub
int i1=i;
int j1=j;
long ret=0;
int l1 = iz-i;
int l2 = io-j;
if(l1<l2 || l2<0) {
return -1000000000;
}
else if(dp[i][j]!=-1) {
return dp[i][j];
}
else if(l2==0) {
dp[i][j]=0;
return 0;
}
else if(l1==l2) {
ret += (int) (solve(dp, zero, one, iz, io, i1+1, j1+1)+Math.abs(zero[i]-one[j]));
}
else {
long ret1=Integer.MAX_VALUE/2;
int[] stack = new int[l1];
int l=0;
while(j<io) {
while(i<iz && zero[i]<one[j]) {
// System.err.println(one[j]+" "+zero[i]+" "+iz+" "+l+" "+l1);
stack[l] = zero[i];
l++;
i++;
}
if(l==0) {
ret += (zero[i]-one[j])+solve(dp, zero, one, iz, io, i+1, j+1);
break;
}
else {
if(i>=iz) {
ret += one[j]-stack[l-1];
l--;
j++;
}
else {
long x1 = one[j]-stack[l-1];
long x2 = zero[i]-one[j];
long s = solve(dp, zero, one, iz, io, i+1, j+1);
long x = x2 + s + ret;
if(x2<x1 && x<ret1 && s>=0) {
ret1=x;
}
ret += x1;
l--;
j++;
}
}
}
if(ret1<ret) {
ret = ret1;
}
}
// System.err.println(ret+" "+i1+" "+j1);
dp[i1][j1]=(int) ret;
return ret;
}
static Node[] merge(Node[] a, Node[] b) {
int m = a.length;
int n = b.length;
Node [] c = new Node[n+m];
int j=0, k=0;
while(j+k<m+n) {
if(j>=m) {
c[j+k] = b[k];
k++;
}
else if(k>=n) {
c[j+k] = a[j];
j++;
}
else {
if(a[j].compareTo(b[k])<0) {
c[j+k] = a[j];
j++;
}
else {
c[j+k] = b[k];
k++;
}
}
}
return c;
}
static Node[] Msort(Node[] unsorted){
int l = unsorted.length;
if(l<=1) {
return unsorted;
}
else {
Node[] Msorted = new Node[l];
Node[] m1 = new Node[l/2];
Node[] m2 = new Node[l-(l/2)];
for(int i=0; i<l; i++) {
if(i<l/2) {
m1[i] = unsorted[i];
}
else {
m2[i-(l/2)] = unsorted[i];
}
}
Msorted = merge(Msort(m1), Msort(m2));
return Msorted;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
4573d3ee088283323242fee3c1e0dcd5
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Comparator;
import java.util.stream.IntStream;
import java.util.ArrayDeque;
import java.util.Set;
import java.util.HashSet;
import java.util.PriorityQueue;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class ____Master {
private static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
m();
}
private static List<Integer> o = new ArrayList<>();
private static List<Integer> u = new ArrayList<>();
private static int n;
private static void m()
{
n =fs.nextInt();
for(int i=0;i<n;i++)
{
int num = fs.nextInt();
if(num==1) o.add(i);
else u.add(i);
}
ol = o.size();
ul = u.size();
long dp[][] = new long[ol][n];
for(int i=0;i<ol;i++) for(int j=0;j<n;j++)dp[i][j]= -1;
int ku = ol;
long ans = helper(0,0,dp);
System.out.println(ans);
}
private static int ol;
private static int ul;
private static long helper(int i,int j,long [][]dp){
if(i==(ol)) return 0;
if(j==ul) return Integer.MAX_VALUE;
// System.out.println(i+" "+j);
if(dp[i][j] != -1) return dp[i][j];
long a = helper(i,j+1,dp);
long b = helper(i+1,j+1,dp) + Math.abs(o.get(i)-u.get(j));
return dp[i][j] = Math.min(a,b);
}
private static int gcd(int a,int b)
{
if(b==0) return a;
return gcd(b,a%b);
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
final private int STRING_SIZE = 1 << 11;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(String fi1ame) {
try{
din = new DataInputStream(new FileInputStream(fi1ame));
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
byte[] buf = new byte[STRING_SIZE]; // string 1gth
int cnt = 0, c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
buf[cnt++] = (byte) c;
c=read();
}
return new String(buf, 0, cnt);
}
public String nextLine() {
byte[] buf = new byte[STRING_SIZE]; // line 1gth
int cnt = 0, c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
buf[cnt++] = (byte) c;
c = read();
}
return new String(buf, 0, cnt);
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
private static StdIn fs = new StdIn();
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
add6b05c4136016392c37735f971d8ea
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Comparator;
import java.util.stream.IntStream;
import java.util.ArrayDeque;
import java.util.Set;
import java.util.HashSet;
import java.util.PriorityQueue;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class ____Master {
private static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
Thread t = new Thread(null,null,"",1<<28)
{
public void run()
{
m();
}
};
try
{
t.start();
t.join();
}
catch(Exception e)
{
System.out.println(e);
}
}
private static List<Integer> o = new ArrayList<>();
private static List<Integer> u = new ArrayList<>();
private static int n;
private static void m()
{
n =fs.nextInt();
for(int i=0;i<n;i++)
{
int num = fs.nextInt();
if(num==1) o.add(i);
else u.add(i);
}
ol = o.size();
ul = u.size();
long dp[][] = new long[ol][n];
for(int i=0;i<ol;i++) for(int j=0;j<n;j++)dp[i][j]= -1;
int ku = ol;
long ans = helper(0,0,dp);
System.out.println(ans);
}
private static int ol;
private static int ul;
private static long helper(int i,int j,long [][]dp){
if(i==(ol)) return 0;
if(j==ul) return Integer.MAX_VALUE;
// System.out.println(i+" "+j);
if(dp[i][j] != -1) return dp[i][j];
long a = helper(i,j+1,dp);
long b = helper(i+1,j+1,dp) + Math.abs(o.get(i)-u.get(j));
return dp[i][j] = Math.min(a,b);
}
private static int gcd(int a,int b)
{
if(b==0) return a;
return gcd(b,a%b);
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
final private int STRING_SIZE = 1 << 11;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(String fi1ame) {
try{
din = new DataInputStream(new FileInputStream(fi1ame));
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
byte[] buf = new byte[STRING_SIZE]; // string 1gth
int cnt = 0, c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
buf[cnt++] = (byte) c;
c=read();
}
return new String(buf, 0, cnt);
}
public String nextLine() {
byte[] buf = new byte[STRING_SIZE]; // line 1gth
int cnt = 0, c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
buf[cnt++] = (byte) c;
c = read();
}
return new String(buf, 0, cnt);
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
private static StdIn fs = new StdIn();
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
28e0236db84a6fa6113ccaeb68329884
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class Armchairs {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] seats = new int[n];
ArrayList<Integer> occupied = new ArrayList<>();
for (int i=0;i<n;i++) {
int temp = scan.nextInt();
seats[i] = temp;
if (temp == 1) occupied.add(i);
}
int occupiedAtFirst = occupied.size();
int[][] dp = new int[n+1][occupiedAtFirst+1]; //look at first i seats and choose j seats to be seated on
for (int i=0;i<=n;i++) {
for (int j=0;j<=occupiedAtFirst;j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
dp[0][0] = 0;
for (int i=0;i<n;i++) {
for (int j=0;j<=occupiedAtFirst;j++) {
int prev = seats[i];
if (dp[i][j] == Integer.MAX_VALUE) continue; //important! because this means that we have not solved for that value yet...
if (prev == 1) { //if my current seat was occupied previously
dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]); //can only move on without choosing
}
else {
dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]);
if (j<occupiedAtFirst) dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j] + Math.abs(occupied.get(j) - i));
}
}
}
System.out.println(dp[n][occupiedAtFirst]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
20a27f04ad3742d1dc0dbf9056b24eca
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.lang.*;
public class Codeforces {
static int t[][]=new int[5005][5005];
static Scanner sr=new Scanner(System.in);
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int dp(int i,int j,ArrayList<Integer>a,ArrayList<Integer>b)
{
if(i>=a.size())
return 0;
if(j>=b.size())
return 99999999;
if(t[i][j]!=-1)
return t[i][j];
int x=Math.abs(a.get(i)-b.get(j))+dp(i+1,j+1,a,b);
int y=dp(i,j+1,a,b);
t[i][j]=Math.min(x,y);
return t[i][j];
}
public static void main(String[] args) throws java.lang.Exception {
StringBuilder ans = new StringBuilder("");
int n=sr.nextInt();
ArrayList<Integer>a=new ArrayList<>();
ArrayList<Integer>b=new ArrayList<>();
for(int i=0;i<n;i++)
{
int x=sr.nextInt();
if(x==1)
a.add(i);
else
b.add(i);
}
for(int i=0;i<5005;i++)
{
for(int j=0;j<5005;j++)
t[i][j]=-1;
}
if(a.size()==0)
System.out.println(0);
else
System.out.println(dp(0,0,a,b));
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
d26f0b29bfdd5ee186f983e00cf0b66f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
int[] a = read_int_array(n);
int count_0 = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
count_0++;
}
}
int count_1 = n - count_0;
int p_0 = 0, p_1 = 0;
int[] index_of_0 = new int[count_0];
int[] index_of_1 = new int[count_1];
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
index_of_0[p_0++] = i;
} else {
index_of_1[p_1++] = i;
}
}
int[][] dp = new int[count_1][count_0];
int[][] min = new int[count_1][count_0];
int current_min;
for (int i = 0; i < count_1; i++) {
current_min = Integer.MAX_VALUE;
for (int j = i; j < count_0; j++) {
if (i != 0) {
dp[i][j] = min[i - 1][j - 1];
} else {
dp[i][j] = 0;
}
dp[i][j] += Math.abs(index_of_1[i] - index_of_0[j]);
current_min = Math.min(dp[i][j], current_min);
min[i][j] = current_min;
}
}
int ans = Integer.MAX_VALUE;
if (count_1 != 0) {
for (int j = count_1 - 1; j < count_0; j++) {
ans = Math.min(ans, dp[count_1 - 1][j]);
}
} else {
ans = 0;
}
out.println(ans);
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static int[] read_int_array(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextInt();
}
return a;
}
private static long[] read_long_array(int len) throws IOException {
long[] a = new long[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextLong();
}
return a;
}
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
f497f28cf618649f634b68c469ac1faa
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class Armchairs {
static ArrayList<Integer> f;
static ArrayList<Integer> u;
static int dp[][];
static int fun(int i, int j){
if(i == f.size()) return 0;
if(j == u.size()) return 99999999;
if(dp[i][j] != -1) return dp[i][j];
int ans1 = fun(i, j+1);
int ans2 = fun(i+1, j+1) + Math.abs(f.get(i)-u.get(j));
return dp[i][j] = Math.min(ans1, ans2);
}
private static int solve(int n, int a[]) {
for (int i = 0; i < n; i++) {
if (a[i]==0)
u.add(i);
else
f.add(i);
}
return fun(0,0);
}
public static void main(String[] args)
throws IOException {
Scanner s = new Scanner();
int t = 1;
StringBuilder ans = new StringBuilder();
int count = 0;
while (t-- > 0) {
int n = s.nextInt();
int a[] = new int[n];
dp=new int[n][n];
for (int i = 0; i < n; i++) {
a[i]=s.nextInt();
}
f=new ArrayList<>();
u=new ArrayList<>();
for( int i=0; i<n; i++) Arrays.fill(dp[i],-1);
ans.append(solve(n, a)).append("\n");
}
System.out.println(ans.toString());
}
static class Scanner {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Scanner() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Scanner(String file_name) throws IOException {
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static long norm(long a, long MOD) {
return ((a % MOD) + MOD) % MOD;
}
public static long msub(long a, long b, long MOD) {
return norm(norm(a, MOD) - norm(b, MOD), MOD);
}
public static long madd(long a, long b, long MOD) {
return norm(norm(a, MOD) + norm(b, MOD), MOD);
}
public static long mMul(long a, long b, long MOD) {
return norm(norm(a, MOD) * norm(b, MOD), MOD);
}
public static long mDiv(long a, long b, long MOD) {
return norm(norm(a, MOD) / norm(b, MOD), MOD);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
4041de6eb2b09d6a7b9ad6d3b0463f2d
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class D {
static int[][] dp;
static int solve(int i,int j,ArrayList<Integer> A,ArrayList<Integer> B) {
if(i==A.size()) {
return 0;
}
if(j==B.size()) {
return 1000000009;
}
if(dp[i][j]!=-1) {
return dp[i][j];
}
int ans=1000000009;
int a=A.get(i);
int b=B.get(j);
ans=Math.min(ans, Math.abs(a-b)+solve(i+1,j+1,A,B));
ans=Math.min(ans, solve(i,j+1,A,B));
return dp[i][j]=ans;
}
public static void main(String[] args){
FastReader sc=new FastReader();
int t=1;
while(t-->0) {
int n=sc.nextInt();
int[] a=new int[n];
ArrayList<Integer> A=new ArrayList<>();
ArrayList<Integer> B=new ArrayList<>();
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
if(a[i]==1) {
A.add(i);
} else {
B.add(i);
}
}
dp=new int[5010][5010];
for(int i=0;i<5010;i++) {
Arrays.fill(dp[i], -1);
}
System.out.println(solve(0,0,A,B));
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
e9c1c45188a4d1fb3287dfdb216e5330
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
//Some of the methods are copied from GeeksforGeeks Website
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static Reader sc=new Reader();
// static FastReader sc=new FastReader(System.in);
static ArrayList<Integer> one;
static ArrayList<Integer> zero;
static long dp[][];
static void ini()
{
for(long a[] : dp)
Arrays.fill(a,-1);
}
static long solve(int i,int j)
{
if(i==one.size()) return 0;
if(j==zero.size()) return int_max;
if(dp[i][j]!=-1) return dp[i][j];
long ans1=Math.abs(one.get(i)-zero.get(j))+solve(i+1,j+1);
long ans2=solve(i,j+1);
return dp[i][j]=Math.min(ans1,ans2);
}
// static int ceilSearch(ArrayList<Integer> arr, int low, int high, int x)
// {
// int mid;
// /* If x is smaller than or equal to the
// first element, then return the first element */
// if(x <= arr.get(low))
// return low;
// /* If x is greater than the last
// element, then return -1 */
// if(x > arr.get(high))
// return -1;
// /* get the index of middle element
// of arr[low..high]*/
// mid = (low + high)/2; /* low + (high - low)/2 */
// /* If x is same as middle element,
// then return mid */
// if(arr.get(mid) == x)
// return mid;
// /* If x is greater than arr[mid], then
// either arr[mid + 1] is ceiling of x or
// ceiling lies in arr[mid+1...high] */
// else if(arr.get(mid) < x)
// {
// if(mid + 1 <= high && x <= arr.get(mid+1))
// return mid + 1;
// else
// return ceilSearch(arr, mid+1, high, x);
// }
// /* If x is smaller than arr[mid],
// then either arr[mid] is ceiling of x
// or ceiling lies in arr[low...mid-1] */
// else
// {
// if(mid - 1 >= low && x > arr.get(mid-1))
// return mid;
// else
// return ceilSearch(arr, low, mid - 1, x);
// }
// }
// static int floorSearch(
// ArrayList<Integer> arr, int low,
// int high, int x)
// {
// // If low and high cross each other
// if (low > high)
// return -1;
// // If last element is smaller than x
// if (x >= arr.get(high))
// return high;
// // Find the middle point
// int mid = (low + high) / 2;
// // If middle point is floor.
// if (arr.get(mid) == x)
// return mid;
// // If x lies between mid-1 and mid
// if (
// mid > 0 && arr.get(mid - 1) <= x && x < arr.get(mid))
// return mid - 1;
// // If x is smaller than mid, floor
// // must be in left half.
// if (x < arr.get(mid))
// return floorSearch(
// arr, low,
// mid - 1, x);
// // If mid-1 is not floor and x is
// // greater than arr[mid],
// return floorSearch(
// arr, mid + 1, high,
// x);
// }
public static void main (String[] args) throws java.lang.Exception
{
try{
int t = 1;// sc.nextInt();
int max=5001;
dp=new long[max][max];
ini();
one=new ArrayList<>();
zero=new ArrayList<>();
while(t-->0)
{
int n=sc.nextInt();
long ans=0;
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]==1)
one.add(i);
else
zero.add(i);
}
// print_int(one);
// print_int(zero);
// for(int i=0;i<one.size();i++)
// {
// int ele=one.get(i);
// int floor=floorSearch(zero,0,zero.size()-1,ele);
// int ceil=ceilSearch(zero,0,zero.size()-1,ele);
// int left=int_max;
// if(floor!=-1)
// left=zero.get(floor);
// int right=int_max;
// if(ceil!=-1)
// right=zero.get(ceil);
// int left_val=Math.abs(ele-left);
// int right_val=Math.abs(ele-right);
// if(left_val<=right_val)
// {
// ans+=left_val;
// zero.remove(floor);
// }
// else
// {
// ans+=right_val;
// zero.remove(ceil);
// }
// }
// out.println(ans);
ans=solve(0,0);
out.println(ans);
}
out.flush();
out.close();
}
catch(Exception e)
{}
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
/*
Map<Long,Long> map=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!map.containsKey(a[i]))
map.put(a[i],1);
else
map.replace(a[i],map.get(a[i])+1);
}
Set<Map.Entry<Long,Long>> hmap=map.entrySet();
for(Map.Entry<Long,Long> data : hmap)
{
}
Iterator<Integer> it = set.iterator();
while(it.hasNext())
{
int x=it.next();
}
*/
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static class Graph
{
int v;
ArrayList<Integer> list[];
Graph(int v)
{
this.v=v;
list=new ArrayList[v+1];
for(int i=1;i<=v;i++)
list[i]=new ArrayList<Integer>();
}
void addEdge(int a, int b)
{
this.list[a].add(b);
}
}
static void DFS(Graph g, boolean[] visited, int u)
{
visited[u]=true;
int v=0;
for(int i=0;i<g.list[u].size();i++)
{
v=g.list[u].get(i);
if(!visited[v])
DFS(g,visited,v);
}
}
// static class Pair
// {
// int x,y;
// Pair(int x,int y)
// {
// this.x=x;
// this.y=y;
// }
// }
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
// Thank You !
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
b1317adb0a6e000d9078b0e00fbb5008
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
/*
*/
public class P2 {
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
//int t=sc.nextInt();
//while(t-->0) {
int n=sc.nextInt();
int a[]=sc.readArray(n);
ArrayList<Integer> free=new ArrayList<>(),used=new ArrayList<>();
for(int i=0;i<n;i++) {
if(a[i]==0)free.add(i);
else used.add(i);
}
n=free.size();
int m=used.size();
int dp[][]=new int[n+1][m+1];
int nax=(int)1e9+ 7;
for(int i=0;i<=n;i++)Arrays.fill(dp[i], nax);
//dp[i][j] = we are at ith free one and jth used one
for(int i=0;i<=n;i++)dp[i][0]=0;
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
//pick this up
dp[i][j] = Math.min(dp[i-1][j-1]+
Math.abs(free.get(i-1)-used.get(j-1)), dp[i][j]);
//dont pick this up
dp[i][j]=Math.min(dp[i][j], dp[i-1][j]);
}
}
//for(int i=0;i<=n;i++)print(dp[i]);
int ans=Integer.MAX_VALUE;
for(int i=m;i<=n;i++)ans=Math.min(ans, dp[i][m]);
System.out.println(ans);
//}
}
static void reverseSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al,Collections.reverseOrder());
for(int i=0;i<a.length;i++)a[i]=al.get(i);
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static void reverse(int a[]) {
int n=a.length;
int b[]=new int[n];
for(int i=0;i<n;i++)b[i]=a[n-1-i];
for(int i=0;i<n;i++)a[i]=b[i];
}
static void reverse(char a[]) {
int n=a.length;
char b[]=new char[n];
for(int i=0;i<n;i++)b[i]=a[n-1-i];
for(int i=0;i<n;i++)a[i]=b[i];
}
static void ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static void print(long a[]) {
for(long e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int a[]=new int [n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
return a;
}
long[] readArrayL(int n) {
long a[]=new long [n];
for(int i=0;i<n;i++) {
a[i]=sc.nextLong();
}
return a;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
184ac3250e47ef250d617b7b9d53cae1
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer> one,zero;
static int[][] dp;
static int func(int i,int j,int n,int m) {
if(dp[i][j]!=-1) return dp[i][j];
if(i==n) return 0;
int present=m-j;
int required=n-i;
if(required>present) return Integer.MAX_VALUE/2;
int ans1=func(i,j+1,n,m);
int ans2=func(i+1,j+1,n,m) +Math.abs(one.get(i)-zero.get(j));
return dp[i][j]=Math.min(ans1, ans2);
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int ttt=1;
// ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
for(int tt=0;tt<ttt;tt++) {
int n=f.nextInt();
int[] l=f.readArray(n);
one=new ArrayList<>();
zero=new ArrayList<>();
for(int i=0;i<n;i++) {
if(l[i]==0) zero.add(i);
else one.add(i);
}
int n1=one.size();
int n2=zero.size();
dp=new int[n1+1][n2+1];
for(int i=0;i<=n1;i++) {
for(int j=0;j<=n2;j++) {
dp[i][j]=-1;
}
}
System.out.println(func(0,0,n1,n2));
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
//Some things to notice
//Check for the overflow
//Binary Search
//Bitmask
//runtime error most of the time is due to array index out of range
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
f273748a3152074923b5ef06e665b595
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class ArmChairs {
static final Random random = new Random();
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n, int size) {
int[] a = new int[size];
for (int i = 0; i < n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] readLongArray(int n, int size) {
long[] a = new long[size];
for (int i = 0; i < n; i++) {
a[i] = this.nextLong();
}
return a;
}
}
static void ruffleSort(long[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
public static void main(String[] args) {
FastReader fs = new FastReader();
int t = 1;
for (int z = 0; z < t; z++) {
int n = fs.nextInt();
List<Integer> empty = new ArrayList<>();
List<Integer> chairs = new ArrayList<>();
for(int i = 0; i < n; i++) {
int status = fs.nextInt();
if(status == 1) chairs.add(i+1);
else empty.add(i+1);
}
int[][] dp = new int[empty.size() + 1][chairs.size() + 1];
dp[0][0] = 0;
for(int i = 1; i <= chairs.size(); i++) dp[0][i] = (int)3e+8;
for(int i = 1; i <= empty.size(); i++) {
for(int j = 1; j <= chairs.size(); j++) {
// Shift jth person to ith chair
dp[i][j] = dp[i-1][j-1] + Math.abs(empty.get(i-1) - chairs.get(j-1));
dp[i][j] = Math.min(dp[i][j], dp[i-1][j]);
}
//System.out.println(i + " " + Arrays.toString(dp[i]));
}
//System.out.println(empty.size() + " " + chairs.size());
System.out.println(dp[empty.size()][chairs.size()]);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
23c894823119f25bb60b56837f658280
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int solve(int leftptr,int rightptr,ArrayList<Integer> left, ArrayList<Integer> right,int[][] dp) {
if (leftptr == left.size()) return 0;
if(rightptr == right.size()) return 1000000000;
if (dp[leftptr][rightptr] != -1) return dp[leftptr][rightptr];
return dp[leftptr][rightptr] = Math.min(solve(leftptr + 1, rightptr + 1,left,right,dp) + Math.abs(left.get(leftptr) - right.get(rightptr)), solve(leftptr, rightptr + 1,left,right,dp));
}
public static void main(String[] args)
{
FastReader s = new FastReader();
int n = s.nextInt();
ArrayList<Integer> left=new ArrayList<>();
ArrayList<Integer> right=new ArrayList<>();
for(int i=0;i<n;i++){
int x=s.nextInt();
if(x==1){
left.add(i);
}else{
right.add(i);
}
}
int[][] dp=new int[n+1][n+1];
for(int i=0;i<n+1;i++){
Arrays.fill(dp[i],-1);
}
System.out.println(solve(0,0,left,right,dp));
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
22aec2b55a4804cab4c5cc59ea448b8c
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long [][] dp;
public static long rec(int i, int j, MyList<Integer> ones, MyList<Integer> zero, int o, int z) {
if(i == o) {
return 0;
} if(j == z) {
return 100000000;
}
if(dp[i][j] != -1) return dp[i][j];
long res = Math.min(Math.abs(ones.get(i) - zero.get(j)) + rec(i + 1, j + 1, ones, zero, o, z), rec(i, j + 1, ones, zero, o, z));
dp[i][j] = res;
return res;
}
public static void solve() {
dp = new long[5000][5000];
for(int i = 0; i < 5000; ++i) {
for(int j = 0; j < 5000; ++j) {
dp[i][j] = -1;
}
}
int n = scanner.nextInt();
MyList<Integer> myList1 = new MyList<Integer>(0) {
@Override
Integer getInput(int index) {
return null;
}
};
MyList<Integer> myList2 = new MyList<Integer>(0) {
@Override
Integer getInput(int index) {
return null;
}
};
int z = 0, o = 0;
for(int i = 0; i < n; ++i) {
int k = scanner.nextInt();
if(k==1) {
myList2.list.add(i);
++o;
} else{
myList1.list.add(i);
++z;
}
}
System.out.println(rec(0, 0, myList2, myList1, o, z));
}
private static FastReader scanner;
static class Pair implements Comparable {
Integer index, value;
public Pair(Integer index, Integer value) {
this.index = index;
this.value = value;
}
public Integer getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
@Override
public int compareTo(Object p) {
return this.getValue().compareTo(((Pair) p).getValue());
}
}
abstract static class MyList<E> {
public ArrayList<E> list;
public MyList(int size) {
list = new ArrayList<>();
for(int i = 0; i < size; ++i){
list.add(null);
}
}
public int size() {
return list.size();
}
public E get(int i) {
return list.get(i);
}
public void set(int i, E val) {
list.set(i, val);
}
public void getInput() {
for(int i = 0; i < size(); ++i) {
list.set(i, getInput(i));
}
}
public void printArray() {
for(int i = 0; i < list.size(); ++i) {
System.out.print(list.get(i).toString());
if(i != list.size() - 1)
System.out.print(" ");
else
System.out.println();
}
}
abstract E getInput(int index);
}
public static void main(String[] args) {
scanner = new FastReader();
int t = 1;
//t = scanner.nextInt();
for(int i = 0; i < t; ++i) {
solve();
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
d162f1c10672c04f64de4f1bbffd37c5
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static long mod = 1000000007;
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int t = 1;
while( t-- > 0) {
int n = sc.nextInt();
ArrayList<Integer> one = new ArrayList<>();
ArrayList<Integer> zero = new ArrayList<>();
for( int i =0 ; i< n ;i++) {
int temp = sc.nextInt();
if( temp == 1) {
one.add(i);
}
else {
zero.add(i);
}
}
n = one.size();
int m = zero.size();
long dp[][] = new long[n][m];
for( int i =0 ; i< n ;i++) {
Arrays.fill(dp[i], -1);
}
out.println(solve( dp , 0 , 0 , n , m , one , zero));
}
out.flush();
}
private static long solve(long[][] dp, int i, int j, int n, int m, ArrayList<Integer> one, ArrayList<Integer> zero) {
if( i == n) {
return 0L;
}
if( j == m) {
return Integer.MAX_VALUE;
}
if( dp[i][j] != -1) {
return dp[i][j];
}
long temp = Math.abs(one.get(i) - zero.get(j)) + solve( dp, i+1 ,j+1 , n , m , one , zero);
temp = Math.min(temp , solve( dp , i, j+1 , n , m , one , zero));
dp[i][j] = temp;
return dp[i][j];
}
/*
* use the hints
* Read the question again
* think of binary search
* look at test cases
* do significant case work
*/
static class DSU{
int n;
int[] leaders,size;
public DSU(int n){
this.n=n;
leaders=new int[n+1];
size=new int[n+1];
for(int i=1;i<=n;i++){
leaders[i]=i;
size[i]=1;
}
}
public int find(int a){
if(leaders[a]==a) return a;
return leaders[a]=find (leaders[a]);
}
public void merge(int a,int b){
a = find(a);
b = find(b);
if (a == b) return;
if (size[a] < size[b]) swap(a, b);
leaders[b] = a;
size[a] += size[b];
}
public void swap(int a,int b){
int temp=a;
a=b;
b=temp;
}
}
static long power(long x, long y, long p)
{
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res%p;
}
public static boolean ifpowof2(long n ) {
return ((n&(n-1)) == 0);
}
static boolean isprime(long x ) {
if( x== 2) {
return true;
}
if( x%2 == 0) {
return false;
}
for( long i = 3 ;i*i <= x ;i+=2) {
if( x%i == 0) {
return false;
}
}
return true;
}
static boolean[] sieveOfEratosthenes(long n) {
boolean prime[] = new boolean[(int)n + 1];
for (int i = 0; i <= n; i++) {
prime[i] = true;
}
for (long p = 2; p * p <= n; p++) {
if (prime[(int)p] == true) {
for (long i = p * p; i <= n; i += p)
prime[(int)i] = false;
}
}
return prime;
}
public List<Integer> goodIndices(int[] nums, int k) {
int n = nums.length;
int fst[] = nextLargerElement(nums, n);
int scnd[] = nextlargerElement(nums, n);
List<Integer> ans = new ArrayList<>();
for( int i = 0 ;i < n; i++) {
if( fst[i] == -1 || scnd[i] == -1) {
continue;
}
if( fst[i]-i >= k && i - scnd[i] >= k) {
ans.add(i);
}
}
return ans;
}
public static int[] nextLargerElement(int[] arr, int n) {
Stack<Integer> stack = new Stack<>();
int rtrn[] = new int[n];
rtrn[n-1] = -1;
stack.push( n-1);
for( int i = n-2 ;i >= 0 ; i--){
int temp = arr[i];
int lol = -1;
while( !stack.isEmpty() && arr[stack.peek()] <= temp){
if(arr[stack.peek()] == temp ) {
lol = stack.peek();
}
stack.pop();
}
if( stack.isEmpty()){
if( lol != -1) {
rtrn[i] = lol;
}
else {
rtrn[i] = -1;
}
}
else{
rtrn[i] = stack.peek();
}
stack.push( i);
}
return rtrn;
}
public static int[] nextlargerElement(int[] arr, int n) {
Stack<Integer> stack = new Stack<>();
int rtrn[] = new int[n];
rtrn[0] = -1;
stack.add( 0);
for( int i = 1 ;i < n ; i++){
int temp = arr[i];
int lol = -1;
while( !stack.isEmpty() && arr[stack.peek()] <= temp){
if(arr[stack.peek()] == temp ) {
lol = stack.peek();
}
stack.pop();
}
if( stack.isEmpty()){
if( lol != -1) {
rtrn[i] = lol;
}
else {
rtrn[i] = -1;
}
}
else{
rtrn[i] = stack.peek();
}
stack.add( i);
}
return rtrn;
}
static void mysort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
int loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static void mySort(long[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
long loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static long rightmostsetbit(long n) {
return n&-n;
}
static long leftmostsetbit(long n)
{
long k = (long)(Math.log(n) / Math.log(2));
return k;
}
static HashMap<Long,Long> primefactor( long n){
HashMap<Long ,Long> hm = new HashMap<>();
long temp = 0;
while( n%2 == 0) {
temp++;
n/=2;
}
if( temp!= 0) {
hm.put( 2L, temp);
}
long c = (long)Math.sqrt(n);
for( long i = 3 ; i <= c ; i+=2) {
temp = 0;
while( n% i == 0) {
temp++;
n/=i;
}
if( temp!= 0) {
hm.put( i, temp);
}
}
if( n!= 1) {
hm.put( n , 1L);
}
return hm;
}
static TreeSet<Long> allfactors(long abs) {
HashMap<Long,Integer> hm = new HashMap<>();
TreeSet<Long> rtrn = new TreeSet<>();
rtrn.add(1L);
for( long i = 2 ;i*i <= abs; i++) {
if( abs% i == 0) {
hm.put( i , 0);
hm.put(abs/i, 0);
}
}
for( long x : hm.keySet()) {
rtrn.add(x);
}
if( abs != 0) {
rtrn.add(abs);
}
return rtrn;
}
public static int[][] prefixsum( int n , int m , int arr[][] ){
int prefixsum[][] = new int[n+1][m+1];
for( int i = 1 ;i <= n ;i++) {
for( int j = 1 ; j<= m ; j++) {
int toadd = 0;
if( arr[i-1][j-1] == 1) {
toadd = 1;
}
prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1];
}
}
return prefixsum;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ac6bdbda8ebb59ddd2a7360bb1b99ca6
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
//package com.example.practice.codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Solution {
public static void main (String [] args) throws IOException {
// Use BufferedReader rather than RandomAccessFile; it's much faster
final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// input file name goes above
StringTokenizer st = new StringTokenizer(input.readLine());
final int n = Integer.parseInt(st.nextToken());
final int[] ns = readArrayInt(n, input);
out.println(calc(n, ns));
out.close(); // close the output file
}
private static long calc(final int N, final int[] ns) {
ArrayList<Integer> fa = new ArrayList<>(), ro = new ArrayList<>();
for (int i=0;i<N;++i){
if (ns[i]==0){
fa.add(i);
}else {
ro.add(i);
}
}
int m = fa.size(), n = ro.size();
if (n==0)return 0;
long[][] dp = new long[n][m];
for (int i=n-1;i>=0;--i){
for (int j=m-1;j>=0;--j){
dp[i][j] = -1;
if (i==n-1 || (j+1<m && dp[i+1][j+1]>=0)) {
dp[i][j] = Math.abs(ro.get(i) - fa.get(j));
if (i+1<n)dp[i][j]+=dp[i+1][j+1];
}
if (j+1<m && dp[i][j+1]>=0){
if (dp[i][j]==-1 || dp[i][j] > dp[i][j+1]){
dp[i][j] = dp[i][j+1];
}
}
}
}
return dp[0][0];
}
private static void printArray(long[] ns, final PrintWriter out){
for (int i=0;i<ns.length;++i){
out.print(ns[i]);
if (i+1<ns.length)out.print(" ");
else out.println();
}
}
private static void printArrayInt(int[] ns, final PrintWriter out){
for (int i=0;i<ns.length;++i){
out.print(ns[i]);
if (i+1<ns.length)out.print(" ");
else out.println();
}
}
private static void printArrayVertical(long[] ns, final PrintWriter out){
for (long a : ns){
out.println(a);
}
}
private static void printArrayVerticalInt(int[] ns, final PrintWriter out){
for (int a : ns){
out.println(a);
}
}
private static void printArray2D(long[][] ns, final int len, final PrintWriter out){
int cnt = 0;
for (long[] kk : ns){
cnt++;
if (cnt > len)break;
for (int i=0;i<kk.length;++i){
out.print(kk[i]);
if (i+1<kk.length)out.print(" ");
else out.println();
}
}
}
private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){
int cnt = 0;
for (int[] kk : ns){
cnt++;
if (cnt > len)break;
for (int i=0;i<kk.length;++i){
out.print(kk[i]);
if (i+1<kk.length)out.print(" ");
else out.println();
}
}
}
private static long[] readArray(final int n, final BufferedReader input) throws IOException{
long[] ns = new long[n];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = Long.parseLong(st.nextToken());
}
return ns;
}
private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{
int[] ns = new int[n];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = Integer.parseInt(st.nextToken());
}
return ns;
}
private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{
long[] ns = new long[n];
for (int i=0;i<n;++i){
ns[i] = Long.parseLong(input.readLine());
}
return ns;
}
private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{
int[] ns = new int[n];
for (int i=0;i<n;++i){
ns[i] = Integer.parseInt(input.readLine());
}
return ns;
}
private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{
long[][] ns = new long[len][];
for (int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(input.readLine());
ArrayList<Long> al = new ArrayList<>();
while (st.hasMoreTokens()){
al.add(Long.parseLong(st.nextToken()));
}
long[] kk = new long[al.size()];
for (int j=0;j<kk.length;++j){
kk[j] = al.get(j);
}
ns[i] = kk;
}
return ns;
}
private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{
int[][] ns = new int[len][];
for (int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(input.readLine());
ArrayList<Integer> al = new ArrayList<>();
while (st.hasMoreTokens()){
al.add(Integer.parseInt(st.nextToken()));
}
int[] kk = new int[al.size()];
for (int j=0;j<kk.length;++j){
kk[j] = al.get(j);
}
ns[i] = kk;
}
return ns;
}
static class SegTree{
int st;
int en;
int mid;
int val1;
int val2;
SegTree left;
SegTree right;
public SegTree(int l, int r, int d){
st = l;
en = r;
mid = (st + en) >> 1;
val1 = val2 = d;
if (st<en){
left = new SegTree(st, mid, d);
right = new SegTree(mid+1, en, d);
}else {
left = right = null;
}
}
public SegTree(int l, int r, int[] ns){
st = l;
en = r;
mid = (st + en) >> 1;
if (st==en){
val1 = val2 = ns[st];
}else {
left = new SegTree(l, mid, ns);
right = new SegTree(mid+1, r, ns);
val1 = Math.min(left.val1, right.val1);
val2 = Math.max(left.val2, right.val2);
}
}
void update(int idx, int v){
if (st==en){
val1 = val2 = v;
}else {
if (idx <= mid){
left.update(idx, v);
}else {
right.update(idx, v);
}
val1 = Math.min(left.val1, right.val1);
val2 = Math.max(left.val2, right.val2);
}
}
int getMin(int l, int r){
if (st==en || (l==st && r==en))return val1;
if (r<=mid){
return left.getMin(l, r);
}
if (l>mid){
return right.getMin(l, r);
}
return Math.min(left.getMin(l, mid), right.getMin(mid+1, r));
}
int getMax(int l, int r){
if (st==en || (l==st && r==en))return val2;
if (r<=mid){
return left.getMax(l, r);
}
if (l>mid){
return right.getMax(l, r);
}
return Math.max(left.getMax(l, mid), right.getMax(mid+1, r));
}
}
static class SparseTable{
int[][] minTable;
int[][] maxTable;
int[] log2;
int n;
public SparseTable(final int[] ns){
n = ns.length;
int m = 0, pre = 0;
while (1<<m < n){
m++;
}
m++;
minTable = new int[n][m];
maxTable = new int[n][m];
log2 = new int[n+1];
for (int i=0;i<n;++i){
minTable[i][0] = ns[i];
maxTable[i][0] = ns[i];
if ((1<<(pre+1)) == i+1){
pre++;
}
log2[i+1] = pre;
}
for (int i=1;i<m;++i){
for (int j=0;j<n;++j){
int r = Math.min(n-1, j+(1<<i)-1);
if (r-(1<<(i-1))+1 <= j){
minTable[j][i] = minTable[j][i-1];
maxTable[j][i] = maxTable[j][i-1];
}else {
minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]);
maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]);
}
}
}
}
int getMin(final int l, final int r){
int d = log2[r-l+1];
return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]);
}
int getMax(final int l, final int r){
int d = log2[r-l+1];
return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7461a4430f0422d60bebb4a1e06f814c
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class Main {
public static int[][] dp;
public static List<Integer> ones, zeros;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
ones = new ArrayList<>();
zeros = new ArrayList<>();
for (int i = 0; i < n; ++i) {
arr[i] = (int) sc.nextInt();
if (arr[i] == 0) {
zeros.add(i);
} else {
ones.add(i);
}
}
int l = zeros.size();
int m = ones.size();
dp = new int[m][l];
for (int i = 0; i < m; ++i) {
Arrays.fill(dp[i], -1);
}
System.out.println(solve(m - 1, l - 1));
}
private static int solve(int x, int y) {
if (x == -1)
return 0;
if (x > y) {
return Integer.MAX_VALUE;
}
if (dp[x][y] != -1) {
return dp[x][y];
}
return dp[x][y] = Math.min(Math.abs(ones.get(x) - zeros.get(y)) + solve(x - 1, y - 1), solve(x, y - 1));
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7dc2b60c20452779abd8ebc8ed2cf99f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
//some updates in import stuff
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
//key points learned
//max space ever that could be alloted in a program to pass in cf
//int[][] prefixSum = new int[201][200_005]; -> not a single array more!!!
//never allocate memory again again to such bigg array, it will give memory exceeded for sure
//believe in your fucking solution and keep improving it!!! (sometimes)
//few things to figure around
//getting better and faster at taking input/output with normal method (buffered reader and printwriter)
//memorise all the key algos! a
public class Main{
static int mod = (int) (Math.pow(10, 9)+7);
static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static final double eps = 1e-10;
static List<Integer> primeNumbers = new ArrayList<>();
public static void main(String[] args) throws IOException {
// MyScanner sc = new MyScanner(); //pretty important for sure -
out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure
//code here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] inp = br.readLine().split(" ");
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(inp[i]);
}
//after this starts the hard part for sure
ArrayList<Integer> ones = new ArrayList<>();
ArrayList<Integer> zeroes = new ArrayList<>();
for(int i= 0; i < n; i++){
if(arr[i] == 1) ones.add(i); else zeroes.add(i);
}
//after this make dp array for start
int[] dp = new int[zeroes.size() + 1]; //simply logical
int[] temp = new int[zeroes.size() + 1];
for(int i = 0; i < ones.size(); i++){
int indexOne = ones.get(ones.size() - i - 1);
temp[zeroes.size() - i] = Integer.MAX_VALUE; //simple one case solve
for(int j = zeroes.size()-i-1 ; j >= 0; j--){
int indexZero = zeroes.get(j);
int currMin = abs(indexOne - indexZero);
temp[j] = min(currMin + dp[j + 1], temp[j + 1]);
}
dp = temp;
temp = new int[zeroes.size() + 1];
}
out.println(dp[0]);
//simply handle all the edge cases for sure
out.close();
}
//Learning to take input this way
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// String[] st = br.readLine().split(" ");
// int v = Integer.parseInt(st[0]);
// int e = Integer.parseInt(st[1]);
// int[] wells = new int[v];
// String[] words = br.readLine().split(" ");
// for (int i = 0; i < wells.length; i++) {
// wells[i] = Integer.parseInt(words[i]);
// }
// int[][] pipes = new int[e][3];
// for (int i = 0; i < e; i++) {
// String[] st1 = br.readLine().split(" ");
// pipes[i][0] = Integer.parseInt(st1[0]);
// pipes[i][1] = Integer.parseInt(st1[1]);
// pipes[i][2] = Integer.parseInt(st1[2]);
// }
//new stuff to learn (whenever this is need for them, then only)
//Lazy Segment Trees
//Persistent Segment Trees
//Square Root Decomposition
//Geometry & Convex Hull
//High Level DP -- yk yk
//String Matching Algorithms
//Heavy light Decomposition
//Updation Required
//Fenwick Tree - both are done (sum)
//Segment Tree - both are done (min, max, sum)
//-----CURRENTLY PRESENT-------//
//Graph
//DSU
//powerMODe
//power
//Segment Tree (work on this one)
//Prime Sieve
//Count Divisors
//Next Permutation
//Get NCR
//isVowel
//Sort (int)
//Sort (long)
//Binomial Coefficient
//Pair
//Triplet
//lcm (int & long)
//gcd (int & long)
//gcd (for binomial coefficient)
//swap (int & char)
//reverse
//primeExponentCounts
//Fast input and output
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//GRAPH (basic structure)
public static class Graph{
public int V;
public ArrayList<ArrayList<Integer>> edges;
//2 -> [0,1,2] (current)
Graph(int V){
this.V = V;
edges = new ArrayList<>(V+1);
for(int i= 0; i <= V; i++){
edges.add(new ArrayList<>());
}
}
public void addEdge(int from , int to){
edges.get(from).add(to);
edges.get(to).add(from);
}
}
//DSU (path and rank optimised)
public static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
Arrays.fill(rank, 1);
Arrays.fill(parent,-1);
this.n = n;
}
public int find(int curr){
if(parent[curr] == -1)
return curr;
//path compression optimisation
return parent[curr] = find(parent[curr]);
}
public void union(int a, int b){
int s1 = find(a);
int s2 = find(b);
if(s1 != s2){
//union by size
if(rank[s1] < rank[s2]){
parent[s1] = s2;
rank[s2] += rank[s1];
}else{
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
}
//with mod
public static long powerMOD(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
x %= mod;
res %= mod;
res = (res * x)%mod;
}
// y must be even now
y = y >> 1; // y = y/2
x%= mod;
x = (x * x)%mod; // Change x to x^2
}
return res%mod;
}
//without mod
public static long power(long x, long y)
{
long res = 1L;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
res = (res * x);
}
// y must be even now
y = y >> 1; // y = y/
x = (x * x);
}
return res;
}
public static class segmentTree{
//so let's make a constructor function for this bad boi for sure!!!
public long[] arr;
public long[] tree;
//COMPLEXITY (normal segment tree, stuff)
//build -> O(n)
//query -> O(logn)
//update -> O(logn)
//update-range -> O(n) (worst case)
//simple iteration and stuff for sure
public segmentTree(long[] arr){
int n = arr.length;
this.arr = new long[n];
for(int i= 0; i < n; i++){
this.arr[i] = arr[i];
}
tree = new long[4*n + 1];
}
//pretty basic idea if you read the code once
//first make child node once
//then form the parent node using them
public void buildTree(int s, int e, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//recursive case
int mid = (s + e)/2;
buildTree(s, mid, 2 * index);
buildTree(mid + 1, e, 2*index + 1);
//the condition we want from children be like this
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
return;
}
//definitely index based 0 query!!!
//only int index = 1!!
//baaki everything is simple as fuck
public long query(int s, int e, int qs , int qe, int index){
//complete overlap
if(s >= qs && e <= qe){
return tree[index];
}
//no overlap
if(qe < s || qs > e){
return Long.MAX_VALUE;
}
//partial overlap
int mid = (s + e)/2;
long left = query( s, mid , qs, qe, 2*index);
long right = query( mid + 1, e, qs, qe, 2*index + 1);
return min(left, right);
}
//gonna do range updates for sure now!!
//let's do this bois!!! (solve this problem for sure)
public void updateRange(int s, int e, int l, int r, long increment, int index){
//out of bounds
if(l > e || r < s){
return;
}
//leaf node
if(s == e){
tree[index] += increment;
return; //behnchoda return tera baap krvayege?
}
//recursive case
int mid = (s + e)/2;
updateRange(s, mid, l, r, increment, 2 * index);
updateRange(mid + 1, e, l, r, increment, 2 * index + 1);
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
}
}
public static class segmentTreeLazy{
//so let's make a constructor function for this bad boi for sure!!!
public long[] arr;
public long[] tree;
public long[] lazy;
//COMPLEXITY (normal segment tree, stuff)
//build -> O(n)
//query-range -> O(logn)
//lazy update-range -> O(logn) (imp)
//simple iteration and stuff for sure
public segmentTreeLazy(long[] arr){
int n = arr.length;
this.arr = new long[n];
for(int i= 0; i < n; i++){
this.arr[i] = arr[i];
}
tree = new long[4*n + 1];
lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO!
}
//pretty basic idea if you read the code once
//first make child node once
//then form the parent node using them
public void buildTree(int s, int e, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//recursive case
int mid = (s + e)/2;
buildTree(s, mid, 2 * index);
buildTree(mid + 1, e, 2*index + 1);
//the condition we want from children be like this
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
return;
}
//definitely index based 0 query!!!
//only int index = 1!!
//baaki everything is simple as fuck
public long queryLazy(int s, int e, int qs, int qe, int index){
//before going down resolve if it exist
if(lazy[index] != 0){
tree[index] += lazy[index];
//non leaf node
if(s != e){
lazy[2*index] += lazy[index];
lazy[2*index + 1] += lazy[index];
}
lazy[index] = 0; //clear the lazy value at current node for sure
}
//no overlap
if(s > qe || e < qs){
return Long.MAX_VALUE;
}
//complete overlap
if(s >= qs && e <= qe){
return tree[index];
}
//partial overlap
int mid = (s + e)/2;
long left = queryLazy(s, mid, qs, qe, 2 * index);
long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1);
return Math.min(left, right);
}
//update range in O(logn) -- using lazy array
public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){
//before going down resolve if it exist
if(lazy[index] != 0){
tree[index] += lazy[index];
//non leaf node
if(s != e){
lazy[2*index] += lazy[index];
lazy[2*index + 1] += lazy[index];
}
lazy[index] = 0; //clear the lazy value at current node for sure
}
//no overlap
if(s > r || l > e){
return;
}
//another case
if(l <= s && e <= r){
tree[index] += inc;
//create a new lazy value for children node
if(s != e){
lazy[2*index] += inc;
lazy[2*index + 1] += inc;
}
return;
}
//recursive case
int mid = (s + e)/2;
updateRangeLazy(s, mid, l, r, inc, 2*index);
updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1);
//update the tree index
tree[index] = Math.min(tree[2*index], tree[2*index + 1]);
return;
}
}
//prime sieve
public static void primeSieve(int n){
BitSet bitset = new BitSet(n+1);
for(long i = 0; i < n ; i++){
if (i == 0 || i == 1) {
bitset.set((int) i);
continue;
}
if(bitset.get((int) i)) continue;
primeNumbers.add((int)i);
for(long j = i; j <= n ; j+= i)
bitset.set((int)j);
}
}
//number of divisors
public static int countDivisors(long number){
if(number == 1) return 1;
List<Integer> primeFactors = new ArrayList<>();
int index = 0;
long curr = primeNumbers.get(index);
while(curr * curr <= number){
while(number % curr == 0){
number = number/curr;
primeFactors.add((int) curr);
}
index++;
curr = primeNumbers.get(index);
}
if(number != 1) primeFactors.add((int) number);
int current = primeFactors.get(0);
int totalDivisors = 1;
int currentCount = 2;
for (int i = 1; i < primeFactors.size(); i++) {
if (primeFactors.get(i) == current) {
currentCount++;
} else {
totalDivisors *= currentCount;
currentCount = 2;
current = primeFactors.get(i);
}
}
totalDivisors *= currentCount;
return totalDivisors;
}
//primeExponentCounts
public static int primeExponentsCount(int n) {
if (n <= 1)
return 0;
int sqrt = (int) Math.sqrt(n);
int remainingNumber = n;
int result = 0;
for (int i = 2; i <= sqrt; i++) {
while (remainingNumber % i == 0) {
result++;
remainingNumber /= i;
}
}
//in case of prime numbers this would happen
if (remainingNumber > 1) {
result++;
}
return result;
}
//now adding next permutation function to java hehe
public static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//finding the value of NCR in O(RlogN) time and O(1) space
public static long getNcR(int n, int r)
{
long p = 1, k = 1;
if (n - r < r) r = n - r;
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = __gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
}
else {
p = 1;
}
return p;
}
//is vowel function
public static boolean isVowel(char c)
{
return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');
}
//to sort the array with better method
public static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
//sort long
public static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
//for calculating binomialCoeff
public static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
//Pair with int int
public static class Pair{
public int a;
public int b;
public int hashCode;
Pair(int a , int b){
this.a = a;
this.b = b;
this.hashCode = Objects.hash(a, b);
}
@Override
public String toString(){
return a + " -> " + b;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair that = (Pair) o;
return a == that.a && b == that.b;
}
@Override
public int hashCode() {
return this.hashCode;
}
}
//Triplet with int int int
public static class Triplet{
public int a;
public int b;
public int c;
Triplet(int a , int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Shortcut function
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
//let's make one for calculating lcm basically
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
//int version for gcd
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//long version for gcd
public static long gcd(long a, long b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//for ncr calculator(ignore this code)
public static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
//swapping two elements in an array
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//for char array
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//reversing an array
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
public static long expo(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second
a = (a * a) % mod;
b = b >> 1;
}
return res;
}
//SOME EXTRA DOPE FUNCTIONS
public static long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
public static long mod_add(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a + b) % m) + m) % m;
}
public static long mod_sub(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a - b) % m) + m) % m;
}
public static long mod_mul(long a, long b, long m) {
a = a % m;
b = b % m;
return (((a * b) % m) + m) % m;
}
public static long mod_div(long a, long b, long m) {
a = a % m;
b = b % m;
return (mod_mul(a, mminvprime(b, m), m) + m) % m;
}
//O(n) every single time remember that
public static long nCr(long N, long K , long mod){
long upper = 1L;
long lower = 1L;
long lowerr = 1L;
for(long i = 1; i <= N; i++){
upper = mod_mul(upper, i, mod);
}
for(long i = 1; i <= K; i++){
lower = mod_mul(lower, i, mod);
}
for(long i = 1; i <= (N - K); i++){
lowerr = mod_mul(lowerr, i, mod);
}
// out.println(upper + " " + lower + " " + lowerr);
long answer = mod_mul(lower, lowerr, mod);
answer = mod_div(upper, answer, mod);
return answer;
}
// long[] fact = new long[2 * n + 1];
// long[] ifact = new long[2 * n + 1];
// fact[0] = 1;
// ifact[0] = 1;
// for (long i = 1; i <= 2 * n; i++)
// {
// fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod);
// ifact[(int)i] = mminvprime(fact[(int)i], mod);
// }
//ifact is basically inverse factorial in here!!!!!(imp)
public static long combination(long n, long r, long m, long[] fact, long[] ifact) {
long val1 = fact[(int)n];
long val2 = ifact[(int)(n - r)];
long val3 = ifact[(int)r];
return (((val1 * val2) % m) * val3) % m;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
57702034c047224aa43431285ca30890
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.util.Map.Entry;
import java.math.*;
import java.sql.Array;
public class Simple{
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return (int) (this.y - other.y);
}
public boolean equals(Pair other){
if(this.x == other.x && this.y == other.y)return true;
return false;
}
public int hashCode(){
return 31*x + y;
}
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
public static class Node{
int root;
ArrayList<Node> al;
Node par;
public Node(int root,ArrayList<Node> al,Node par){
this.root = root;
this.al = al;
this.par = par;
}
}
// public static int helper(int arr[],int n ,int i,int j,int dp[][]){
// if(i==0 || j==0)return 0;
// if(dp[i][j]!=-1){
// return dp[i][j];
// }
// if(helper(arr, n, i-1, j-1, dp)>=0){
// return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp));
// }
// return dp[i][j] = helper(arr, n, i-1, j,dp);
// }
// public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){
// levelcount[count]++;
// for(Integer x : al.get(node)){
// dfs(al, levelcount, x, count+1);
// }
// }
public static long __gcd(long a, long b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static class DSU{
int n;
int par[];
int rank[];
public DSU(int n){
this.n = n;
par = new int[n+1];
rank = new int[n+1];
for(int i=1;i<=n;i++){
par[i] = i ;
rank[i] = 0;
}
}
public int findPar(int node){
if(node==par[node]){
return node;
}
return par[node] = findPar(par[node]);//path compression
}
public void union(int u,int v){
u = findPar(u);
v = findPar(v);
if(rank[u]<rank[v]){
par[u] = v;
}
else if(rank[u]>rank[v]){
par[v] = u;
}
else{
par[v] = u;
rank[u]++;
}
}
}
public static int helper(ArrayList<Integer> one,ArrayList<Integer> zero,int i,int j,int dp[][],int nn,int mm){
if(i<0)return 0;
if(dp[i+1][j+1]!=-1)return dp[i+1][j+1];
if(i<j){
return dp[i+1][j+1] = Math.min(helper(one, zero, i-1, j-1, dp, nn, mm)+ Math.abs(one.get(i)-zero.get(j)), helper(one, zero, i, j-1, dp, nn, mm));
}
else{
return dp[i+1][j+1] = helper(one, zero, i-1, j-1, dp, nn, mm)+ Math.abs(one.get(i)-zero.get(j));
}
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t = 1;
for(int t1 = 1;t1<=t;t1++){
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++)arr[i] = s.nextInt();
ArrayList<Integer> one = new ArrayList<>();
ArrayList<Integer> zero = new ArrayList<>();
for(int i=0;i<n;i++){
if(arr[i]==1){
one.add(i);
}
else{
zero.add(i);
}
}
// System.out.println(one.toString());
// System.out.println(zero.toString());
int nn = one.size();
int mm = zero.size();
int dp[][] = new int[nn+1][mm+1];
for(int i=0;i<=nn;i++){
for(int j=0;j<=mm;j++){
dp[i][j] = -1;
}
}
int ans = helper(one, zero, nn-1, mm-1, dp, nn, mm);
System.out.println(ans);
// for(int j=0;j<=mm;j++){
// if(dp[1][j]!=-1){
// ans = Math.min(ans, dp[1][j]);
// }
// }
// for(int i=0;i<=nn;i++){
// for(int j=0;j<=mm;j++){
// System.out.print(dp[i][j]+" ");
// }
// System.out.println();
// }
// if(ans==Integer.MAX_VALUE)System.out.println(0);
// else
// System.out.println(ans);
}
}
}
/*
4 2 2 7
0 2 5
-2 3
5
0*x1 + 1*x2 + 2*x3 + 3*x4
*/
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
27b17337c0326cf3dea8c345c1163a4f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
int[] a = read_int_array(n);
int count_0 = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
count_0++;
}
}
int count_1 = n - count_0;
int p_0 = 0, p_1 = 0;
int[] index_of_0 = new int[count_0];
int[] index_of_1 = new int[count_1];
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
index_of_0[p_0++] = i;
} else {
index_of_1[p_1++] = i;
}
}
int[][] dp = new int[count_1][count_0];
int[][] min = new int[count_1][count_0];
int current_min;
for (int i = 0; i < count_1; i++) {
current_min = Integer.MAX_VALUE;
for (int j = i; j < count_0; j++) {
if (i != 0) {
dp[i][j] = min[i - 1][j - 1];
} else {
dp[i][j] = 0;
}
dp[i][j] += Math.abs(index_of_1[i] - index_of_0[j]);
current_min = Math.min(dp[i][j], current_min);
min[i][j] = current_min;
}
}
int ans = Integer.MAX_VALUE;
if (count_1 != 0) {
for (int j = count_1 - 1; j < count_0; j++) {
ans = Math.min(ans, dp[count_1 - 1][j]);
}
} else {
ans = 0;
}
out.println(ans);
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static int[] read_int_array(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextInt();
}
return a;
}
private static long[] read_long_array(int len) throws IOException {
long[] a = new long[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextLong();
}
return a;
}
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7a7e0693470563d452641d13c637da3d
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Armchairs {
static final int INF = 1000000000;
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, false);
int N = reader.nextInt();
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = reader.nextInt();
}
List<Integer> occupied = new ArrayList<>();
for (int i = 0; i < N; i++) {
if (A[i] == 1) occupied.add(i);
}
int K = occupied.size();
int[][] dp = new int[N + 1][K + 1];
for (int[] row : dp) Arrays.fill(row, INF);
dp[0][0] = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j <= K; j++) {
int x = j < K ? occupied.get(j) : 0;
dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j]);
if (j + 1 <= K && A[i] == 0) {
dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j] + Math.abs(i - x));
}
}
}
writer.println(dp[N][K]);
writer.close();
System.exit(0);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
b2cfa554be736d52789b9b967913b597
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
//package edu109div2;
import java.util.LinkedList;
import java.util.Scanner;
public class D_Armchairs {
public static void main(String[] args) {
int maxCost = 5000;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
boolean[] occ = new boolean[n];
int numOcc = 0;
for (int i = 0; i < n; i++) {
if (in.nextInt() == 1) {
occ[i] = true;
numOcc++;
}
}
// sorted by position
var occs = new int[numOcc];
var frees = new int[n - numOcc];
var c = 0;
var d = 0;
for (int i = 0; i < n; i++) {
if(occ[i]) {
occs[c++] = i;
} else {
frees[d++] = i;
}
}
if(numOcc == 0) {
System.out.println(0);
return;
}
int[][] dp = new int[occs.length][frees.length];
dp[0][0] = Math.abs(occs[0] - frees[0]);
for (int j = 1; j < frees.length ; j++) {
var dis = Math.abs(frees[j] - occs[0]);
dp[0][j] = Math.min(dis, dp[0][j-1]);
}
for (int i = 1; i < occs.length ; i++) {
// Match first occupied with first free (only one matching is
// possible)
dp[i][i] = dp[i - 1][i - 1] + Math.abs(occs[i] - frees[i]);
for (int j = i + 1; j < frees.length; j++) {
int chooseMatching =
dp[i-1][j-1] + Math.abs(occs[i] - frees[j]);
int skip = dp[i][j-1];
dp[i][j] = Math.min(chooseMatching, skip);
}
}
System.out.println(dp[occs.length - 1][frees.length - 1]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
46d585b8156bf9a2d7e45d3c2ddea631
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class taskd {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
taskd sol = new taskd();
sol.solve(in, out);
out.flush();
}
void solve(FastScanner in, PrintWriter out) {
int n = in.nextInt();
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = in.nextInt();
if (x == 1) {
a.add(i);
} else {
b.add(i);
}
}
long dp[][] = new long[a.size() + 5][b.size() + 5];
for (int i = a.size()-1; i >= 0; i--) {
dp[i][b.size()] = Integer.MAX_VALUE;
for (int j = b.size()-1; j >= 0; j--) {
dp[i][j] = dp[i][j + 1];
dp[i][j] = Math.min(dp[i][j], Math.abs(a.get(i) - b.get(j)) + dp[i + 1][j + 1]);
}
}
out.println(dp[0][0]);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
float nextFloat() { return Float.parseFloat(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
a14ae9a83f99202c16a447e42c37ad14
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int a[]=new int[n];
ArrayList<Integer> list=new ArrayList<>();
ArrayList<Integer> space=new ArrayList<>();
for(int i=0;i<n;i++)
{
a[i]=input.nextInt();
if(a[i]==1)
{
list.add(i);
}
else
{
space.add(i);
}
}
int pre[]=new int[space.size()];
for(int i=0;i<list.size();i++)
{
if(i==0)
{
int min=Integer.MAX_VALUE;
for(int j=0;j<space.size();j++)
{
pre[j]=Math.abs(list.get(i)-space.get(j));
min=Math.min(min,pre[j]);
pre[j]=min;
}
}
else
{
int arr[]=new int[space.size()];
for(int j=0;j<i;j++)
{
arr[j]=Integer.MAX_VALUE;
}
int min=Integer.MAX_VALUE;
for(int j=i;j<space.size();j++)
{
int v=Math.abs(list.get(i)-space.get(j));
v+=pre[j-1];
arr[j]=v;
min=Math.min(min,v);
arr[j]=min;
}
for(int j=0;j<space.size();j++)
{
pre[j]=arr[j];
}
}
}
out.println(pre[space.size()-1]);
}
out.close();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
66ebb7526cd959ba80334ab9d5fa86ee
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.Scanner;
public class Armchairs {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int[] chairs = new int[num];
int numOne = 0;
for (int i = 0; i < num; i++) {
chairs[i] = scanner.nextInt();
if (chairs[i] == 1) numOne++;
}
if (numOne == 0) {
System.out.println(0);
return;
}
int one = 0;
int zero = 0;
int[] ones = new int[numOne];
int[] zeros = new int[num - numOne];
for (int i = 0; i < num; i++) {
if (chairs[i] == 0) zeros[zero++] = i;
else ones[one++] = i;
}
long[][] nums = new long[numOne][num - numOne];
for (int c = 0; c < num - numOne; c++)
nums[0][c] = Math.abs(ones[0] - zeros[c]);
for (int r = 1; r < numOne; r++) {
long min = nums[r - 1][r - 1];
for (int c = r; c < num - numOne; c++) {
min = Math.min(nums[r - 1][c - 1], min);
nums[r][c] = min + Math.abs(ones[r] - zeros[c]);
}
}
Long result = Long.MAX_VALUE;
for (long min: nums[numOne - 1]) {
if (min > 0) result = Math.min(result, min);
}
System.out.println(result);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
75f7bf92cbd9cba997cb65a506a6fdce
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class E1525D {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
ArrayList<Integer> occupied = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
if (arr[i] == 1) occupied.add(i);
}
int[][] dp = new int[n + 1][occupied.size() + 1];
for (int[] row : dp) Arrays.fill(row, (int) 1e9);
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
dp[i][0] = 0;
for (int j = 1; j <= occupied.size(); j++) {
dp[i][j] = dp[i - 1][j];
if (arr[i - 1] == 0)
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + Math.abs(i - 1 - occupied.get(j - 1)));
}
}
System.out.println(dp[n][occupied.size()]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
38971ad27ba66930a93bb56622e25b9f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class Main {
static final long MOD=1000000007;
static final long MOD1=998244353;
static long ans=0;
//static ArrayList<Integer> ans=new ArrayList<>();
public static void main(String[] args){
PrintWriter out = new PrintWriter(System.out);
InputReader sc=new InputReader(System.in);
int N = sc.nextInt();
int[] A = sc.nextIntArray(N);
ArrayList<Integer> a1 = new ArrayList<Integer>();
ArrayList<Integer> a2 = new ArrayList<Integer>();
for (int i = 0; i < A.length; i++) {
if (A[i]==0) {
a1.add(i);
}else {
a2.add(i);
}
}
int[][] dp = new int[a1.size()+1][a2.size()+1];
for (int i = 0; i < dp.length; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE/2);
}
dp[0][0] = 0;
for (int i = 1; i <= a1.size() ; i++) {
int pos1 = a1.get(i-1);
for (int j = 0; j <= a2.size(); j++) {
dp[i][j] = dp[i-1][j];
if (j-1>=0) {
int pos2 = a2.get(j-1);
dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1] + Math.abs(pos1-pos2));
}
}
}
System.out.println(dp[a1.size()][a2.size()]);
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
12f9582122bbed99c84cc485653569c7
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class D_1525 {
static int INF = (int)1e9;
static int n, m;
static int[] full, free;
static int[][] memo;
public static int dp(int i, int j) {
if(i == n)
return 0;
if(j == m)
return INF;
if(memo[i][j] != -1)
return memo[i][j];
return memo[i][j] = Math.min(dp(i, j + 1), Math.abs(free[j] - full[i]) + dp(i + 1, j + 1));
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int l = sc.nextInt();
int[] array = sc.nextIntArray(l);
n = 0;
for(int i = 0; i < l; i++)
if(array[i] == 1)
n++;
m = l - n;
full = new int[n];
free = new int[m];
int ind1 = 0, ind2 = 0;
for(int i = 0; i < l; i++)
if(array[i] == 0)
free[ind2++] = i;
else
full[ind1++] = i;
memo = new int[n][m];
for(int[] i : memo)
Arrays.fill(i, -1);
pw.println(dp(0, 0));
pw.flush();
}
public static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static int[] shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
1483738b9da1a3cdab1b6cb384057d63
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
OutputWriter out = new OutputWriter(System.out);
// Always print a trailing "\n" and close the OutputWriter as shown at the end of your output
// example:
int n=scn.nextInt();
ArrayList<Integer> arr0=new ArrayList<Integer>();
ArrayList<Integer> arr1=new ArrayList<Integer>();
for(int i=0;i<n;i++){
int val=scn.nextInt();
if(val==1){
arr1.add(i);
}
else{
arr0.add(i);
}
}
int[] dp=new int[arr0.size()+1];
int[] min=new int[arr0.size()+1];
for(int i=0;i<arr1.size();i++){
for(int j=i;j<arr0.size()-arr1.size()+1+i;j++){
dp[j+1]=Math.abs(arr1.get(i)-arr0.get(j))+min[j];
}
min[i+1]=dp[i+1];
for(int j=i+1;j<arr0.size()-arr1.size()+1+i;j++){
min[j+1]=Math.min(min[j],dp[j+1]);
}
}
out.print(min[arr0.size()]+"");
out.close();
}
// fast input
static class Scanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Scanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
} catch (Exception e) {
throw(new RuntimeException());
}
}
return tokenizer.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
}
// fast output
static class OutputWriter {
BufferedWriter writer;
public OutputWriter(OutputStream stream) {
writer = new BufferedWriter(new OutputStreamWriter(stream));
}
public void print(int i) throws IOException { writer.write(i); }
public void print(String s) throws IOException { writer.write(s); }
public void print(char[] c) throws IOException { writer.write(c); }
public void close() throws IOException { writer.close(); }
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
c29d7fe314e892d3d60df2a857db6f49
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
try (BufferedInputStream in = new BufferedInputStream(System.in);
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) {
Scanner sc = new Scanner(in).useLocale(Locale.US);
// int T = sc.nextInt();
// for (int t = 0; t < T; t++) {
// }
// 14:56-
int n = sc.nextInt();
List<Integer> player = new ArrayList<>();
List<Integer> open = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (sc.nextInt() == 1) {
player.add(i);
} else {
open.add(i);
}
}
int[][] dp = new int[open.size() + 1][player.size() + 1];
int INF = Integer.MAX_VALUE >> 1;
for (int i = 1; i < dp[0].length; i++) dp[0][i] = INF;
for (int i = 1; i <= player.size(); i++) {
for (int j = 1; j <= open.size(); j++) {
dp[j][i] = dp[j - 1][i - 1] + Math.abs(player.get(i - 1) - open.get(j - 1));
dp[j][i] = Math.min(dp[j][i], dp[j - 1][i]);
}
}
out.println(dp[open.size()][player.size()]);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ac6ef1be75bb7db620d0eb780739bec0
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
//package Div_2B_Problems;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.ArrayList;
public class Armchairs {
static ArrayList<Integer> one;
static ArrayList<Integer> zero;
public static void main(String args[]) {
FastScanner fs=new FastScanner();
int n=fs.nextInt();
int []arr=new int[n];
one=new ArrayList<>();
zero=new ArrayList<>();
for(int i=0;i<arr.length;i++) {
arr[i]=fs.nextInt();
if(arr[i]==1)
one.add(i);
else zero.add(i);
}
int [][]dp=new int[arr.length][arr.length];
for(int i=0;i<arr.length;i++)
Arrays.fill(dp[i], -1);
System.out.println(dfs(dp,0,0));
}
public static int dfs(int [][]dp,int i,int j) {
//System.out.println(i+" "+j);
if(i>=one.size())
return 0;
if(j>=zero.size())
return (int)(1e9);
if(dp[i][j]!=-1)
return dp[i][j];
dp[i][j]=Math.min(Math.abs(one.get(i)-zero.get(j))+dfs(dp,i+1,j+1), dfs(dp,i,j+1));
return dp[i][j];
}
private static int[] readArray(int n) {
// TODO Auto-generated method stub
return null;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
db837e4dd7dc6bbc789313aa6acd4a50
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class Solution {
public static int minMoves(int[] input) {
List<Integer> people = new ArrayList<Integer>();
List<Integer> chairs = new ArrayList<Integer>();
for (int i = 0; i < input.length; i++) {
if (input[i] == 1) {
people.add(i);
} else {
chairs.add(i);
}
}
int[] memo = new int[chairs.size() + 1];
for (int p = 1; ((!people.isEmpty()) && (p <= people.size())); p++) {
int prev = memo[p];
memo[p] = memo[p - 1] + Math.abs(people.get(p - 1) - chairs.get(p - 1));
for (int c = p + 1; c <= chairs.size(); c++) {
int tmp = memo[c];
memo[c] = Math.min(memo[c - 1], prev + Math.abs(people.get(p - 1) - chairs.get(c - 1)));
prev = tmp;
}
}
return memo[memo.length - 1];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] input = new int[n];
for (int i = 0; i < n; i++) {
input[i] = sc.nextInt();
}
System.out.println(Solution.minMoves(input));
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
75a5d5b1951d91e0588c0da825f11948
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int cases = Integer.parseInt(br.readLine());
//while(cases-- > 0) {
int n = Integer.parseInt(br.readLine());
String[] str = br.readLine().split(" ");
int[] a = new int[n];
int k = 0;
ArrayList<Integer> pos = new ArrayList<>();
for(int i=0; i<n; i++) {
a[i] = Integer.parseInt(str[i]);
if(a[i] == 1) {
k++;
pos.add(i);
}
}
int[][] dp = new int[n+1][k+1];
for(int i=0; i<=n; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
dp[0][0] = 0;
for(int i=0; i<n; i++) {
for(int j=0; j<=k; j++) {
if(dp[i][j] == Integer.MAX_VALUE) {
continue;
}
dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]);
if(j < k && a[i] == 0) {
dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j]+Math.abs(pos.get(j)-i));
}
}
}
System.out.println(dp[n][k]);
//}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
2e8fc58f89b415073ed324b4b6cf5b78
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static int solve(int dp[][],int i,int j,ArrayList<Integer> al1,ArrayList<Integer> al2) {
if(dp[i][j]!=-1) return dp[i][j];
if(i==al1.size())
return 0;
if(j==al2.size()) {
return 1000000000;
}
int shift=Math.abs(al1.get(i)-al2.get(j))+solve(dp,i+1,j+1,al1,al2);
int noShift=solve(dp,i,j+1,al1,al2);
dp[i][j]=Math.min(shift,noShift);
return dp[i][j];
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
// int t=sc.nextInt();
// while(t-->0) {
int n=sc.nextInt();
int a[]=new int[n];
int count=0;
ArrayList<Integer> al1=new ArrayList<>();
ArrayList<Integer> al2=new ArrayList<>();
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
if(a[i]==1) {
al1.add(i);
count++;
}
else {
al2.add(i);
}
}
int dp[][]=new int[5005][5005];
for(int i=0;i<5005;i++) {
for(int j=0;j<5005;j++) {
dp[i][j]=-1;
}
}
// System.out.println(al1);
// System.out.println(al2);
//System.out.println(count);
int ans=solve(dp,0,0,al1,al2);
System.out.println(ans);
// }
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
0e8038093f0b39f492a4bb21db6a6d7f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author Pradyumn Agrawal (coderbond007)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DArmchairs solver = new DArmchairs();
solver.solve(1, in, out);
out.close();
}
static class DArmchairs {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] pos = new int[n];
int ptr = 0;
for (int i = 0; i < n; ++i) {
if (a[i] == 1) {
pos[ptr++] = i;
}
}
pos = Arrays.copyOf(pos, ptr);
int[][] dp = new int[n + 1][ptr + 1];
ArrayUtils.fill(dp, Integer.MAX_VALUE);
dp[0][0] = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= ptr; ++j) {
if (dp[i][j] == Integer.MAX_VALUE) continue;
dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j]);
if (j < ptr && a[i] == 0) {
dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j] + Math.abs(pos[j] - i));
}
}
}
out.println(dp[n][ptr]);
}
}
static class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
}
static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
202a098f6b0f58834fc22f5d59c1d81c
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
public class B{
static int n;
static int m;
static long[][] dp;
static int[] pos;
static int[] emp;
static long make(int i, int j)
{
if(i>=n)return 0;
if(j>=m)return (long)(1e12);
if(dp[i][j] != -1)return dp[i][j];
long ans = Math.abs(pos[i]-emp[j]) + make(i+1,j+1);
ans = Math.min(ans,make(i,j+1));
return dp[i][j] = ans;
}
public static void main(String[] args)
{
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
n = fs.nextInt();
List<Integer> temp = new ArrayList();
List<Integer> pip = new ArrayList();
int[] arr = new int[n];
for(int i=0;i<n;i++)
{
arr[i] = fs.nextInt();
if(arr[i] == 0)
{
temp.add(i);
}
else
{
pip.add(i);
}
}
n = pip.size(); m = temp.size();
int start = 0;
pos = new int[pip.size()];
for(int i:pip)pos[start++] = i;
start = 0;
emp = new int[temp.size()];
for(int i:temp)emp[start++] = i;
dp = new long[n][m];
for(int i=0;i<n;i++)for(int j=0;j<m;j++)dp[i][j] = -1;
out.println(make(0,0));
out.close();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
public static int[] sort(int[] arr)
{
List<Integer> temp = new ArrayList();
for(int i:arr)temp.add(i);
Collections.sort(temp,Collections.reverseOrder());
int start = 0;
for(int i:temp)arr[start++]=i;
return arr;
}
public static char[] rev(char[] arr)
{
char[] ret = new char[arr.length];
int start = arr.length-1;
for(char i:arr)ret[start--] = i;
return ret;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
7c5ccb46736e0c9370aa75b4a8045a9d
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int cnt = n;
boolean[] non = new boolean[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
if(Integer.parseInt(st.nextToken()) == 0) {
non[i] = true;
cnt--;
}
}
int x = 0;
int y = 0;
int[] location = new int[cnt];
int[] rlocation = new int[n-cnt];
for(int i = 0; i < n; i++) {
if(!non[i]) {
location[x] = i;
x++;
}else{
rlocation[y] = i;
y++;
}
}
int[][] dp = new int[(n-cnt)+1][cnt+1];
Arrays.fill(dp[0], 100000000);
dp[0][0] = 0;
for(int i = 0; i < n-cnt; i++) {
//System.out.println("HIT");
if(i < (n-cnt))
Arrays.fill(dp[i+1], 100000000);
for(int j = 0; j < cnt; j++) {
if(i < (n-cnt)) {
dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]);
dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j] + Math.abs(rlocation[i] - location[j]));
//System.out.println(dp[i+1][j+1] + " " + dp[i][j] + " " + j + " " + rlocation[i] + " " + location[j]);
}
}
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < (n-cnt)+1; i++) {
min = Math.min(dp[i][cnt], min);
}
System.out.println(min);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
34205452c0b443641a884304a66b63ec
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.*;
/*AUTHOR - SHIVAM GUPTA */
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE ,JUst keep faith in ur strengths ..................................................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2,ALL ARE PAIRWISE COPRIME,THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other, two consecutive even have always gcd = 2 ;
// Rectangle r = new Rectangle(int x , int y,int widht,int height)
//Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))
//BY DEFAULT Priority Queue is MIN in nature in java
//to use as max , just push with negative sign and change sign after removal
// We can make a sieve of max size 1e7 .(no time or space issue)
// In 1e7 starting nos we have about 66*1e4 prime nos
// In 1e6 starting nos we have about 78,498 prime nos
public class Main
{
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0){ sum = sum + (int)( n %10) ; n /= 10 ; }
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start<end){ int temp = arr[start] ;arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ;}
}
//////////////////////////////////////////////////////////////////////////////////
static long factorial(long a)
{
if(a== 0L || a==1L)return 1L ;
return a*factorial(a-1L) ;
}
///////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ; else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int a, int b )
{
if(b==0)return a ;else return gcd(b,a%b) ;
}
public static long gcd(long a, long b )
{
if(b==0)return a ;else return gcd(b,a%b) ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;int ans = lcm(temp ,c) ;return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);return (a/gc)*b ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);return (a/gc)*b;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)return false ;
for(long i = 2L; i*i <= n ;i++){ if(n% i ==0){return false; } }
return true ;
}
static boolean isPrime(int n)
{
if(n==1)return false ;
for(int i = 2; i*i <= n ;i++){ if(n% i ==0){return false ; } }
return true ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime and 1 // TRUE == COMPOSITE
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N // size - 1e7(at max)
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ; i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j){ int temp = arr[i] ;arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ;}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ; long prefixsum = 0 ; long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))count = count + map.get(prefixsum -sum) ;
if(map.containsKey(prefixsum )) map.put(prefixsum , map.get(prefixsum) +1 );
else map.put(prefixsum , 1L );
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{l++ ;}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)list.add(i) ;
else{ list.add(i) ;list.add(n/i) ; }
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n) list.add(i) ;
else{ list.add(i) ; list.add(n/i) ; }
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 1000001;
static int spf[] = new int[MAXN];
static void sieve()
{
for (int i=1; i<MAXN; i++) spf[i] = i; // ALL NOS HAVE SPF[i] =i AT START
for (int i=4; i<MAXN; i+=2) //ALL EVEN NOS HAVE SPF[i] = 2
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j) spf[j] = i;
}
}
}
static ArrayList<Integer> getPrimeFactorization(int x)
{
ArrayList<Integer> ret = new ArrayList<Integer>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ; dp[0] = arr[0] ;long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0) dp[i] = dp[i-1] + arr[i] ; else dp[i] = arr[i] ;
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{ if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;dp[0] = arr[0] ; long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0) dp[i] = dp[i-1] + arr[i] ; else dp[i] = arr[i] ;
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(int a ,int b)
{
//time comp : o(logn)
long x = (long)(a) ; long n = (long)(b) ;
if(n==0)return 1 ;if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)ans = ans *x ;
n = n/2L ;x = x*x ;
}
return ans ;
}
public static long power(long a ,long b)
{
//time comp : o(logn)
long x = (a) ;long n = (b) ;
if(n==0)return 1L ;if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)ans = ans *x ;
n = n/2L ; x = x*x ;
}
return ans ;
}
//////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;int start=0;int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;int start=0;int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1; int start=0; int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei, int f)
{
for(int i = si ; i <= ei ; i++){ out.print(arr[i] +" ") ; } if(f==1)out.println() ;
}
public static void printArray(long[] arr , int si ,int ei, int f)
{
for(int i = si ; i <= ei ; i++){ out.print(arr[i] +" ") ; } if(f==1)out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ;
}
out.println() ;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
a = a % p ;
if(a == 0)return 0L ;
if(x==0)return 1L;
if(x==1)return a;
long res = 1L;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x =x/2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod p. //(assuming p is prime).
return modPow(a, p-2, p);
}
static long[] factorial = new long[1000001] ;
static void modfac(long mod)
{
factorial[0]=1L ; factorial[1]=1L ;
for(int i = 2; i<= 1000000 ;i++)
{
factorial[i] = factorial[i-1] *(long)(i) ;
factorial[i] = factorial[i] % mod ;
}
}
static long modBinomial(long n, long r, long p) {
// calculates C(n,r) mod p (assuming p is prime).
if(n < r) return 0L ;
long num = factorial[(int)(n)] ;
long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ;
long ans = num*(modInverse(den,p)) ;
ans = ans % p ;
return ans ;
}
static void update(int val , long[] bit ,int n)
{
for( ; val <= n ; val += (val &(-val)) )
{
bit[val]++ ;
}
}
static long query(int val , long[] bit , int n)
{
long ans = 0L;
for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val];
return ans ;
}
static int countSetBits(long n)
{
int count = 0;
while (n > 0) {
n = (n) & (n - 1L); count++;
}
return count;
}
static int abs(int x)
{ if(x<0)x=-x ; return x ; }
static long abs(long x)
{ if(x<0)x=-x ; return x ; }
////////////////////////////////////////////////////////////////////////////////////////////
// calculate total no of nos greater than or equal to key in sorted array arr
static int bs(int[] arr, int s ,int e ,int key)
{
if( s> e)return 0 ;
int mid = (s+e)/2 ;
if(arr[mid] <key) return bs(arr ,mid+1,e , key) ;
else {return bs(arr ,s ,mid-1, key) + e-mid+1;}
}
// static ArrayList<Integer>[] adj ;
// static int mod= 1000000007 ;
static class pair {
int u;
int v;
public pair(int u,int v) {
this.u = u ; this.v=v;
}
}
static class Dsu
{
int n ;int[] par ; int[] size ;
public Dsu(int n)
{
this.n = n ;
par = new int[n] ;
size = new int[n] ;
for(int i = 0 ; i< n ;i++)
{
par[i] =i ;size[i] =1 ;
}
}
// cheack if given element is root element of its set
public boolean isRoot(int x)
{
return par[x] == x ;
}
// find root of given set
public int findRoot(int x)
{
if(par[x] == x)
{
return par[x] ;
}
par[x] = findRoot(par[x]) ; //path compression
return par[x] ;
}
public boolean unionSet(int a, int b)
{
int rootA = findRoot(a);
int rootB=findRoot(b) ;
if(rootA==rootB)return true ;//they are alraedy present in same set/connected already(in graph)
if(size[rootA] > size[rootB])
{
size[rootA] += size[rootB] ;
par[rootB] =rootA ;
}
else{
size[rootB] += size[rootA] ;
par[rootA] =rootB ;
}
return false ; // means we union both the sets now
}
}
static int zerosize = 0;
static int onesize = 0 ;
static ArrayList<Integer> o = new ArrayList<>() ;
static ArrayList<Integer> z = new ArrayList<>() ;
static long[][] dp ;
static long cal(int i , int j) // (one, zero)
{
if(i== onesize)return 0 ;
if(j==zerosize)return 100000000000L;
if(dp[i][j] != -1)return dp[i][j] ;
long opt1 = cal(i+1,j+1) + Math.abs(o.get(i)-z.get(j));
long opt2 = cal(i,j+1) ;
dp[i][j] = Math.min(opt1,opt2) ;
return dp[i][j] ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//DEBUGGING -
// 1 - I/O - CHECK PRINTING OF NEXT LINE , READ INPUT , EXTRA LINE PRINT.
//2-OVERFLOW ERROR.
//3 -STATIC VARIABLE INITIALIZATION (INT MAINLIY)
//4-DIVISION ERROR(FLOOR/CEIL) or DIVIDE BY ZERO
//5-MOD -(MOD BY 1 OR 0 )
// DOUBLE LOOP/TRIPLE LOOP BREAK (SEE IF DO NOT BREAK ALL THE LOOPS IF U GET ANS EARLIER)
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Integer> listx = new ArrayList<>() ;
ArrayList<Integer> listy = new ArrayList<>() ;
HashMap<Integer,Integer> map = new HashMap<>() ;
HashMap<Integer,Integer> mapx = new HashMap<>() ;
HashMap<Integer,Integer> mapy = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
Set<Integer> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);// Collections.reverse(list) ;
//int bit =Integer.bitCount(n);// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
int testcase = 1;
//testcase = scn.nextInt() ;
for(int testcases =1 ; testcases <= testcase ;testcases++)
{
//adj = new ArrayList[n] ;
// for(int i = 0; i< n; i++)
// {
// adj[i] = new ArrayList<Integer>();
// }
// long n = scn.nextLong() ;
//String s = scn.next() ;
//Dsu dsu = new Dsu(n) ;
int n= scn.nextInt() ;
for(int i = 0 ; i < n;i++){
int t = scn.nextInt() ;
if(t ==0)z.add(i) ;
else o.add(i) ;
}
zerosize =z.size() ;
onesize = o.size() ;
dp = new long[onesize][zerosize] ;
for(int i = 0 ; i < dp.length ;i++)
{
for(int j = 0 ; j < dp[0].length ; j++)dp[i][j] =-1 ;
}
out.println(cal(0,0)) ;
//out.println(ans) ;
//out.println("Case #" + testcases + ": " + ans ) ;
//out.println("@") ;
sb.delete(0 , sb.length()) ;
list.clear() ;listx.clear() ;listy.clear() ;
map.clear() ;mapx.clear() ;mapy.clear() ;
set.clear() ;setx.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{ solve() ; }
}
class Pair
{
int first ;int second ;
public Pair(int x, int y)
{
this.first = x ;this.second = y ;
}
@Override
public boolean equals(Object obj)
{
if(obj == this)return true ;
if(obj == null)return false ;
if(this.getClass() != obj.getClass()) return false ;
Pair other = (Pair)(obj) ;
if(this.first != other.first)return false ;
if(this.second != other.second)return false ;
return true ;
}
@Override
public int hashCode()
{
return this.first^this.second ;
}
@Override
public String toString() {
String ans = "" ;ans += this.first ; ans += " "; ans += this.second ;
return ans ;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
61a7efcd70b10b74fc62c86698f75da1
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
public class Solution {
public static boolean sorted(int[] array) {
for(int i=0; i<array.length-1; i++) {
if(array[i] > array[i+1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int dp[][] = new int[n+1][n+1];
int a[] = new int[n];
ArrayList<Integer> ones = new ArrayList<>();
ArrayList<Integer> zeros = new ArrayList<>();
for(int i=0; i<n; i++) {
a[i] = in.nextInt();
if(a[i] == 0) {
zeros.add(i);
}
else {
ones.add(i);
}
}
for(int i=1; i<=ones.size(); i++) {
for(int j=0; j<=zeros.size(); j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
for(int i=1; i<=ones.size(); i++) {
for(int j=i; j<=zeros.size(); j++) {
dp[i][j] = Math.min(dp[i][j], dp[i][j-1]);
dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1] + (int)(Math.abs(ones.get(i-1) - zeros.get(j-1))));
}
}
System.out.println(dp[ones.size()][zeros.size()]);
in.close();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
e7b0e90a40436c83afc5249e81f8e16e
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static long dp[][];
static long recurse(int arr0[],int arr1[],int i,int j){
if(i==arr1.length) return 0;
if(j==arr0.length) return 100000000000l;
if(dp[i][j]>=0) return dp[i][j];
long min;
//for(int i=p;i<arr1.length;i++){
min=Math.min(recurse(arr0,arr1,i+1,j+1)+Math.abs(arr1[i]-arr0[j]),
recurse(arr0,arr1,i,j+1));
// }
return dp[i][j]=min;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=1;
// t=sc.nextInt();
//int t=Integer.parseInt(br.readLine());
while(--t>=0){
int n=sc.nextInt();
dp=new long[n+5][n+5];
int occ=0,unocc=0;
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
if(a[i]==0) unocc++;
else occ++;
}
for(int i=0;i<n+5;i++)for(int j=0;j<n+5;j++) dp[i][j]=-1;
int arr0[]=new int[unocc];
int arr1[]=new int[occ];
unocc=0;occ=0;
for(int i=0;i<n;i++){
if(a[i]==1)arr1[occ++]=i;
else arr0[unocc++]=i;
}
// for(int i=0;i<occ;i++)System.out.println(arr1[i]);
System.out.println(recurse(arr0,arr1,0,0));
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 11
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
aeb0c0a7eb71d061e6b46ca045eafea2
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TaskD {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int[] a = new int[n];
int zeroCount = 0;
for(int i=0;i<n;i++){
a[i]=in.nextInt();
if(a[i]==0){
zeroCount++;
}
}
int [] aj = new int[zeroCount];
int [] ai = new int[n-zeroCount];
{
int ii=0;
int jj=0;
for(int i=0;i<n;i++){
if(a[i]==0){
aj[jj++]=i;
}else{
ai[ii++]=i;
}
}
}
int solution = solution(ai,aj);
out.println(solution);
out.flush();
out.close();
in.close();
}
private static int solution(final int[] ai,final int[] aj) {
int [] prev = new int[aj.length+1];
int [] cur = new int[aj.length+1];
for(int i=0;i<aj.length;i++){
prev[i]=0;
}
final int INF = 1_000_000_000;
int min;
for(int i=1;i<=ai.length;i++){
for(int j=0;j<i;j++){
cur[j]=INF;
}
for(int j=i;j<=aj.length;j++){
cur[j]=cur[j-1];
min = prev[j-1]+Math.abs(aj[j-1]-ai[i-1]);
if(cur[j]>min){
cur[j]=min;
}
}
int [] t = prev;
prev = cur;
cur = t;
}
return prev[aj.length];
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
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());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
long[] readLongArr(int n) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = Long.parseLong(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
fbbe686fef47ca6fd11c5b7030989be4
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TaskD {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int[] a = new int[n];
int zeroCount = 0;
for(int i=0;i<n;i++){
a[i]=in.nextInt();
if(a[i]==0){
zeroCount++;
}
}
int [] aj = new int[zeroCount];
int [] ai = new int[n-zeroCount];
{
int ii=0;
int jj=0;
for(int i=0;i<n;i++){
if(a[i]==0){
aj[jj++]=i;
}else{
ai[ii++]=i;
}
}
}
int solution = solution(ai,aj);
out.println(solution);
out.flush();
out.close();
in.close();
}
private static int solution(final int[] ai,final int[] aj) {
// final int [][] dp = new int[ai.length+1][aj.length+1];
// dp[0][0]=0;
int [] prev = new int[aj.length+1];
int [] cur = new int[aj.length+1];
for(int i=0;i<aj.length;i++){
prev[i]=0;
}
final int INF = 1_000_000_000;
for(int i=1;i<=ai.length;i++){
for(int j=0;j<i;j++){
cur[j]=INF;
}
for(int j=i;j<=aj.length;j++){
cur[j]=Math.min(prev[j-1]+Math.abs(aj[j-1]-ai[i-1]),
cur[j-1]);
}
// System.out.println(Arrays.toString(cur));
int [] t = prev;
prev = cur;
cur = t;
}
return prev[aj.length];
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
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());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
long[] readLongArr(int n) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = Long.parseLong(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
a6f2cac593b2a7aee13e361b79097f22
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TaskD {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int[] a = new int[n];
int zeroCount = 0;
for(int i=0;i<n;i++){
a[i]=in.nextInt();
if(a[i]==0){
zeroCount++;
}
}
int [] aj = new int[zeroCount];
int [] ai = new int[n-zeroCount];
{
int ii=0;
int jj=0;
for(int i=0;i<n;i++){
if(a[i]==0){
aj[jj]=i;
jj++;
}else{
ai[ii]=i;
ii++;
}
}
}
int solution = solution(ai,aj);
out.println(solution);
out.flush();
out.close();
in.close();
}
private static int solution(final int[] ai,final int[] aj) {
int [][] dp = new int[ai.length+1][aj.length+1];
dp[0][0]=0;
for(int i=0;i<aj.length;i++){
dp[0][i]=0;
}
final int INF = 1_000_000_000;
for(int i=1;i<=ai.length;i++){
for(int j=0;j<i;j++){
dp[i][j]=INF;
}
for(int j=i;j<=aj.length;j++){
dp[i][j]=Math.min(dp[i-1][j-1]+Math.abs(aj[j-1]-ai[i-1]), dp[i][j-1]);
}
}
return dp[ai.length][aj.length];
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
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());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
long[] readLongArr(int n) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = Long.parseLong(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
183812edac67e5e829a1da285602b607
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TaskD {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int[] a = new int[n];
int zeroCount = 0;
for(int i=0;i<n;i++){
a[i]=in.nextInt();
if(a[i]==0){
zeroCount++;
}
}
int [] aj = new int[zeroCount];
int [] ai = new int[n-zeroCount];
{
int ii=0;
int jj=0;
for(int i=0;i<n;i++){
if(a[i]==0){
aj[jj]=i;
jj++;
}else{
ai[ii]=i;
ii++;
}
}
}
int solution = solution(ai,aj);
out.println(solution);
out.flush();
out.close();
in.close();
}
private static int solution(final int[] ai,final int[] aj) {
int [][] dp = new int[ai.length+1][aj.length+1];
dp[0][0]=0;
for(int i=0;i<aj.length;i++){
dp[0][i]=0;
}
final int INF = 1_000_000_000;
for(int i=1;i<=ai.length;i++){
for(int j=0;j<i;j++){
dp[i][j]=INF;
}
}
for(int i=1;i<=ai.length;i++){
for(int j=i;j<=aj.length;j++){
dp[i][j]=Math.min(dp[i-1][j-1]+Math.abs(aj[j-1]-ai[i-1]), dp[i][j-1]);
}
}
return dp[ai.length][aj.length];
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
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());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
long[] readLongArr(int n) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = Long.parseLong(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
8b166b22a16907a7d3ffb3e3d1452b97
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.ObjectInputStream.GetField;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.sound.sampled.ReverbType;
public class Edu109 {
static PrintWriter out;
static Scanner sc;
static ArrayList<int[]>q,w,x;
static ArrayList<Integer>adj[];
static HashSet<Integer>primesH;
static boolean prime[];
//static ArrayList<Integer>a;
static HashSet<Long>tmp;
static int[][][]dist;
static boolean[]v;
static int[]a,b,c,d;
static Boolean[][]dp;
static char[][]mp;
static int A,B,n,m,h,ans,sum;
//static String a,b;
static long oo=(long)1e9+7;
public static void main(String[]args) throws IOException {
sc=new Scanner(System.in);
out=new PrintWriter(System.out);
//A();
//B();
//C();
D();
//E();
//F();
//G();
out.close();
}
private static void A() throws IOException {
int t=ni();
while(t-->0) {
int k=ni();
int ans=0;
for(int i=1;i<=100;i++) {
if((i*100)%k==0) {
ans=i*100/k;break;
}
}
ol(ans);
}
}
static void B() throws IOException {
int t=ni();
while(t-->0) {
int n=ni();
a=nai(n);
boolean isSorted=true,one=a[0]==1;
int pos=0;
for(int i=1;i<n;i++) {
if(a[i]<a[i-1])isSorted=false;
if(a[i]==1)pos=i;
}
boolean ok=true;
for(int i=pos+1;i<n;i++) {
if(a[i]<a[i-1])ok=false;
}
boolean lst=a[0]==n;
boolean fir=a[n-1]==1;
if(isSorted)ol(0);
else if(lst&&fir)ol(3);
else if(lst||fir)ol(2);
else if(a[0]==1||a[n-1]==n)ol(1);
else ol(2);
// if(isSorted)ol(0);
// else out.println(fl&&lst?3:((one?1:2)-(ok?1:0)+(lst?1:0)));
}
}
static void C() throws IOException{
int t=ni();
while(t-->0) {
int n=ni();
int m=ni();
a=nai(n);
TreeMap<Integer, Integer>tr=new TreeMap<Integer, Integer>();
for(int i=0;i<n;i++)tr.put(a[i], i);
char[]mv=new char[n];
for(int i=0;i<n;i++) {
String s=ns();
mv[i]=s.charAt(0);
}
long[]ans=new long[n];
Arrays.fill(ans, -1);
PriorityQueue<Integer>lodd=new PriorityQueue<Integer>();
PriorityQueue<Integer>lev=new PriorityQueue<Integer>();
PriorityQueue<Integer>rodd=new PriorityQueue<Integer>();
PriorityQueue<Integer>rev=new PriorityQueue<Integer>();
for(int i=0;i<n;i++) {
if(a[i]%2==0) {
if(mv[i]=='L')lev.add(a[i]);
else rev.add(a[i]);
}else {
if(mv[i]=='L')lodd.add(a[i]);
else rodd.add(a[i]);
}
}
PriorityQueue<Integer>par[]=new PriorityQueue[4];
par[0]=rev;par[1]=rodd;par[2]=lev;par[3]=lodd;
for(int i=0;i<2;i++){
while(par[i].size()>=1&&par[i+2].size()>=1) {
int r=par[i].poll(),l=par[i+2].poll();
int d1=(l-r)/2;
if(l<r) {
d1=clc(l,r,m);
}
int dr=Integer.MAX_VALUE,dl=Integer.MAX_VALUE;
if(par[i].size()==1) {
dr=m-par[i].peek()+(par[i].peek()-r)/2;
}
if(!par[i+2].isEmpty()) {
dl=(par[i+2].peek()+l)/2;
}
int cur=Math.min(d1, Math.min(dl, dr));
if(cur==d1) {
ans[tr.get(r)]=ans[tr.get(l)]=cur;
}
else if(cur==dr) {
ans[tr.get(r)]=ans[tr.get(par[i].poll())]=cur;
par[i+2].add(l);
}else {
ans[tr.get(l)]=ans[tr.get(par[i+2].poll())]=cur;
par[i].add(r);
}
}
}
for(int i=0;i<4;i++) {
if(i<2&&par[i].size()%2==1)par[i].poll();
while(par[i].size()>1) {
int x=par[i].poll(),y=par[i].poll();
int val=0;
if(i<2) {
val=m-y+(y-x)/2;
}else {
val=(x+y)/2;
}
ans[tr.get(x)]=ans[tr.get(y)]=val;
}
}
for(int i=0;i<n;i++) {
out.print(ans[i]+" ");
}ol("");
}
}
private static int clc(int l, int r, int m) {
int b1=0,b2=m;
int ans=0;
if(l>m-r) {
ans+=l;
b2=2*m - l -r;// m-(l-m+r) -> m-l+m-r
}else {
ans+=m-r;
b1=m-r-l;
}
return ans+(b2-b1)/2;
}
private static Boolean dp(int i, int j) {
if(j>sum/2)return false;
if(i==x.size()) {
return sum/2==j;
}
if(dp[i][j]!=null)return dp[i][j];
return dp[i][j]=dp(i+1,j+x.get(i)[0])||dp(i+1,j);
}
static boolean isPrime(long n) {
if(n==2)return true;
if(n<2||n%2==0)return false;
for(long i=3L;i*i<n;i+=2l) {
long rem=(n%i);
if(rem==0)return false;
}
return true;
}
static long[][]mem;
static int ones;
static ArrayList<Integer>pos;
static void D() throws IOException {
int t=1;
while(t-->0) {
n=ni();
a=nai(n);
mem=new long[n][n];
ones=0;
pos=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
Arrays.fill(mem[i], -1);
if(a[i]==1)pos.add(i);
}
ones=pos.size();
long ans=solve(0,0);
out.println(ans);
}
}
private static long solve(int i, int j) {
if(i==n||j>=ones)return j==ones?0:(long)1e14;
if(mem[i][j]!=-1)return mem[i][j];
long lv=solve(i+1,j);
if(a[i]==0) {
int pr=Math.abs(i-pos.get(j));
lv=Math.min(lv, pr+solve(i+1,j+1));
}
return mem[i][j]=lv;
}
private static int bfs(int i, int j,int k) {
boolean [][]vis=new boolean[dist.length][dist[0].length];
Queue<int[]>q=new LinkedList<int[]>();
int mn=Integer.MAX_VALUE;
q.add(new int[] {i,j,0,0});
int[]dx=new int[] {-1,1,0,0};
int[]dy=new int[] {0,0,1,-1};
while(!q.isEmpty()) {
int []x=q.poll();
vis[x[0]][x[1]]=true;
int c=x[2];
if(c>k/2)continue;
if(c>0&&k%c==0&&(k/c)%2==0) {
mn=Math.min(mn,x[3]*k/c );
}
for(int a=0;a<4;a++) {
int nx=x[0]+dx[a];
int ny=x[1]+dy[a];
if(valid(nx,ny)&&!vis[nx][ny]) {
q.add(new int[] {nx,ny,c+1,x[3]+dist[x[0]][x[1]][a]});
}
}
}
return mn;
}
private static boolean valid(int nx, int ny) {
return nx>=0&&nx<dist.length&&ny>=0&&ny<dist[0].length;
}
static int gcd (int a, int b) {
return b==0?a:gcd (b, a % b);
}
static void E() throws IOException {
int t=ni();
while(t-->0) {
}
}
static void F() throws IOException {
int t=ni();
while(t-->0) {
}
}
static void CC() throws IOException {
for(int kk=2;kk<21;kk++) {
ol(kk+" -------");
int n=kk;
int k=n-2;
int msk=1<<k;
int[]a=new int[k];
for(int i=0;i<a.length;i++)a[i]=i+2;
int mx=1;
int ms=0;
for(int i=1;i<msk;i++) {
long prod=1;
int cnt=0;
for(int j=0;j<a.length;j++) {
if(((i>>j)&1)!=0) {
prod*=a[j];
cnt++;
}
}
if(cnt>=mx&&prod%n==1) {
mx=cnt;
ms=i;
}
}
ol(mx==1?mx:mx+1);
out.print(1+" ");
long pr=1;
for(int j=0;j<a.length;j++) {
if(((ms>>j)&1)!=0) {
out.print(a[j]+" ");
pr*=a[j];
}
}
ol("");
ol("Prod: "+pr);
ol(n+"*"+((pr-1)/n)+" + "+1);
}
}
static int ni() throws IOException {
return sc.nextInt();
}
static double nd() throws IOException {
return sc.nextDouble();
}
static long nl() throws IOException {
return sc.nextLong();
}
static String ns() throws IOException {
return sc.next();
}
static int[] nai(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
return a;
}
static long[] nal(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextLong();
return a;
}
static int[][] nmi(int n,int m) throws IOException{
int[][]a=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=sc.nextInt();
}
}
return a;
}
static long[][] nml(int n,int m) throws IOException{
long[][]a=new long[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=sc.nextLong();
}
}
return a;
}
static void o(String x) {
out.print(x);
}
static void ol(String x) {
out.println(x);
}
static void ol(int x) {
out.println(x);
}
static void disp1(int []a) {
for(int i=0;i<a.length;i++) {
out.print(a[i]+" ");
}
out.println();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public boolean hasNext() {return st.hasMoreTokens();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready(); }
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
13cf95c2db95b9447d6996585aa25c89
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
/*
Challenge 1: Newbie to CM in 1year (Dec 2021 - Nov 2022) 5* Codechef
Challenge 2: CM to IM in 1 year (Dec 2022 - Nov 2023) 6* Codechef
Challenge 3: IM to GM in 1 year (Dec 2023 - Nov 2024) 7* Codechef
Goal: Become better in CP!
Key: Consistency and Discipline
Desire: SDE @ Google USA
Motto: Do what i Love <=> Love what you do
*/
public class Coder {
static StringBuffer str=new StringBuffer();
static int n;
static int a[];
static long dp[][];
static long solve(int i, int j){
// System.out.println(i+" "+j);
if(i==n) return 0;
if(j==n) return Integer.MAX_VALUE;
if(dp[i][j]!=-1) return dp[i][j];
int jt=j+1, it=i+1;
while(jt<n && a[jt]==1) jt++;
while(it<n && a[it]==0) it++;
long ans=Math.min(Math.abs(i-j)+solve(it, jt), solve(i, jt));
return dp[i][j]=ans;
}
public static void main(String[] args) throws java.lang.Exception {
boolean lenv=false;
BufferedReader bf;
PrintWriter pw;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
// int q1 = Integer.parseInt(bf.readLine().trim());
// while (q1-->0) {
n=Integer.parseInt(bf.readLine().trim());
String s[]=bf.readLine().trim().split("\\s+");
a=new int[n];
for(int i=0;i<n;i++) a[i]=Integer.parseInt(s[i]);
dp=new long[n][n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++) dp[i][j]=-1;
int i=0, j=0;
while(i<n && a[i]==0) i++;
while(j<n && a[j]==1) j++;
str.append(solve(i, j)).append("\n");
// }
pw.print(str);
pw.flush();
// System.out.print(str);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
2d4cf76f93173ab5ec0107e325ff3dc1
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class _109D {
static BufferedReader br;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
int n = readInt();
int arr[] = readIntarray();
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for(int i = 0; i < n; i++){
if(arr[i] == 1){
a.add(i);
}else{
b.add(i);
}
}
if(a.size() == 0){
System.out.println("0");
return;
}
int [][] dp = new int[a.size()][b.size()];
for(int i = 0; i < a.size(); i++){
for(int j = i; j < b.size(); j++) {
if (j == 0) {
dp[i][j] = Math.abs(a.get(i) - b.get(j));
} else if (i == 0) {
dp[i][j] = Math.min(dp[i][j - 1], Math.abs(a.get(i) - b.get(j)));
} else if (i == j) {
dp[i][j] = dp[i - 1][j - 1] + Math.abs(a.get(i) - b.get(j));
} else {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(a.get(i) - b.get(j)));
}
}
}
System.out.println(dp[a.size() - 1][b.size() - 1]);
}
static int readInt() throws IOException {
return Integer.parseInt(br.readLine());
}
static long readLong() throws IOException {
return Long.parseLong(br.readLine());
}
static int[] readIntarray() throws IOException {
String[] _a = br.readLine().split(" ");
int[] _res = new int[_a.length];
for (int i = 0; i < _a.length; i++) {
_res[i] = Integer.parseInt(_a[i]);
}
return _res;
}
static long[] readLongarray() throws IOException {
String[] _a = br.readLine().split(" ");
long[] _res = new long[_a.length];
for (int i = 0; i < _a.length; i++) {
_res[i] = Long.parseLong(_a[i]);
}
return _res;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
ecad1a87d23cc5a16a1accc202b624ee
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
//int t = sc.ni();while(t-->0)
solve();
w.close();
}
static List<Integer> taken = new ArrayList<>(), empty = new ArrayList<>();
static int[][] dp;
/*static int fill(int at, int used) {
if(used == taken.size()) {
return 0;
}
if(dp[at][used] != 0) return dp[at][used];
int ahead = ima;
for(int i = at+1; i < empty.size(); i++) {
int remEmpty = empty.size()-i;
if(remEmpty+used < taken.size()) break;
ahead = Math.min(ahead, Math.abs(taken.get(used)-empty.get(i))+fill(i, used+1));
}
return dp[at][used] = ahead;
}*/
static void solve() throws IOException {
int n = sc.ni();
for(int i = 0; i < n; i++) {
int curr = sc.ni();
if(curr == 0) {
empty.add(i);
} else taken.add(i);
}
if(taken.size() == 0) {
w.p(0);
return;
}
int sz = empty.size();
dp = new int[sz][sz];
dp[0][0] = Math.abs(taken.get(0)-empty.get(0));
for(int at = 0; at < sz; at++) {
if(at == 0) continue;
for(int used = 0; used < sz; used++) {
if(used > at || used >= taken.size()) break;
if(used == 0) {
dp[at][used] = Math.min(dp[at-1][used], Math.abs(taken.get(0)-empty.get(at)));
} else if(dp[at-1][used] != 0) {
dp[at][used] = Math.min(dp[at-1][used],
dp[at-1][used-1]+Math.abs(taken.get(used)-empty.get(at)));
} else {
dp[at][used] = dp[at-1][used-1]+Math.abs(taken.get(used)-empty.get(at));
}
}
}
w.p(dp[empty.size()-1][taken.size()-1]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
bc7a71482c8098e4f87b2e3ad4a56b7c
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pranay2516
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DArmchairs solver = new DArmchairs();
solver.solve(1, in, out);
out.close();
}
static class DArmchairs {
ArrayList<Integer>[] arr;
long[][] dp;
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readArray(n);
int mx = 5001;
dp = new long[mx][mx];
for (int i = 0; i < mx; ++i) {
Arrays.fill(dp[i], -1);
}
arr = new ArrayList[2];
for (int i = 0; i < 2; ++i) {
arr[i] = new ArrayList<>();
}
for (int i = 0; i < n; ++i) {
arr[a[i]].add(i);
}
out.println(go(0, 0));
}
long go(int i, int j) {
if (i == arr[1].size()) return 0;
if (j == arr[0].size()) return (long) 1e9;
if (dp[i][j] != -1) return dp[i][j];
long pick = Math.abs(arr[0].get(j) - arr[1].get(i)) + go(i + 1, j + 1);
long leave = go(i, j + 1);
dp[i][j] = Math.min(leave, pick);
return dp[i][j];
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
79412d4a04502b039351991099fe3483
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static long gdc(long a, long b) {
if (b > a) {
long t = a;
a = b;
b = t;
}
while (a % b != 0) {
long t = a % b;
a = b;
b = t;
}
return b;
}
public static void test() {
int n = 6;
Random r = new Random();
int t = 1000;
while (t-- > 0) {
int ones = r.nextInt(n / 2) + 1;
int v[] = new int[n];
for (int i = 0; i < n; i++) {
if (ones > 0) {
v[i] = r.nextInt(2);
if (v[i] == 1) {
ones--;
}
} else {
v[i] = 0;
}
}
int smart = cc(n, v);
int greedy = c(n, v);
if (smart != greedy) {
System.out.println(smart + " " + greedy + " " + Arrays.toString(v));
break;
}
}
System.out.println("done!");
}
public static void main(String[] args) throws IOException {
// test();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1024 * 1024 * 2);
// int t = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
// while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
int[] v = readArrayLine(br.readLine(), n);
sb.append(cc(n, v)).append('\n');
// }
System.out.println(sb.toString());
}
private static int cc(int n, int[] v) {
List<Integer> ones = new ArrayList<>();
List<Integer> zeros = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (v[i] == 1) {
ones.add(i);
} else {
zeros.add(i);
}
}
if (ones.size() == 0) {
return 0;
}
int[][] d = new int[ones.size()][zeros.size()];
for (int i = 0; i < ones.size(); i++) {
if (i == 0) {
for (int j = 0; j < zeros.size(); j++) {
d[i][j] = Math.abs(ones.get(i) - zeros.get(j));
}
} else {
int minCost = Integer.MAX_VALUE;
for (int j = 0; j < i; j++) {
minCost = Math.min(d[i - 1][j], minCost);
d[i][j] = Integer.MAX_VALUE;
}
for (int j = i; j < zeros.size(); j++) {
d[i][j] = Math.abs(ones.get(i) - zeros.get(j)) + minCost;
minCost = Math.min(d[i - 1][j], minCost);
}
}
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < zeros.size(); j++) {
min = Integer.min(min, d[ones.size() - 1][j]);
}
return min;
}
private static int c(int n, int[] v) {
LinkedList<Integer> zeros = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (v[i] == 0) {
zeros.add(i);
}
}
int ones = n - zeros.size();
int cost = 0;
for (int i = 0; i < n; i++) {
if (v[i] == 1) {
if (ones == zeros.size()) {
int j = zeros.poll();
ones--;
cost += Math.abs(j - i);
} else {
int min = Integer.MAX_VALUE;
int jj = -1;
for (int j : zeros) {
int dist = Math.abs(j - i);
if (dist < min) {
min = dist;
jj = j;
}
}
zeros.remove((Integer) jj);
ones--;
cost += min;
}
}
}
return cost;
}
private static int b(int n, int[] v) {
boolean sorted = true;
for (int i = 1; i < n; i++) {
if (v[i] < v[i - 1]) {
sorted = false;
break;
}
}
int count = 0;
if (!sorted) {
if (v[0] == 1 || v[n - 1] == n) {
count = 1;
} else if (v[0] == n && v[n - 1] == 1) {
count = 3;
} else {
count = 2;
}
}
return count;
}
private static long solve() {
return 0;
}
public static int[] readArrayLine(String line, int n) {
return readArrayLine(line, n, null, 0);
}
private static int[] readArrayLine(String line, int n, int array[], int pos) {
int[] ret = array == null ? new int[n] : array;
int start = 0;
int end = line.indexOf(' ', start);
for (int i = pos; i < pos + n; i++) {
if (end > 0)
ret[i] = Integer.parseInt(line.substring(start, end));
else
ret[i] = Integer.parseInt(line.substring(start));
start = end + 1;
end = line.indexOf(' ', start);
}
return ret;
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
d112bc8d254fb72e32b5e57175a02f00
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class D_Edu_Round_109 {
public static long MOD = 1000000007;
static int[][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
int[] pre = new int[n];
int[] count = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
dp = new int[n][n];
for (int[] a : dp) {
Arrays.fill(a, -1);
}
for (int i = n - 1; i >= 0; i--) {
pre[i] += (1 - data[i]);
count[i] += data[i];
if (i + 1 < n) {
pre[i] += pre[i + 1];
count[i] += count[i + 1];
}
}
out.println(cal(0, 0, pre, count, data));
out.close();
}
static int cal(int index, int pos, int[] pre, int[] count, int[] data) {
if (index == data.length) {
return 0;
}
if (count[index] == 0) {
return 0;
}
if (pos == data.length) {
return data.length * data.length;
}
if (count[index] > pre[pos]) {
return data.length * data.length;
}
if (data[index] == 0) {
return cal(index + 1, pos, pre, count, data);
}
if (data[pos] == 1) {
return cal(index, pos + 1, pre, count, data);
}
if (dp[index][pos] != -1) {
return dp[index][pos];
}
int result = Integer.min(cal(index + 1, pos + 1, pre, count, data) + abs(index - pos), cal(index, pos + 1, pre, count, data));
return dp[index][pos] = result;
}
static int abs(int v) {
return v < 0 ? -v : v;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x;
String y;
public Point(int start, String end) {
this.x = start;
this.y = end;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
311ce6aa03125d78b9f997e46dee785f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class D_Edu_Round_109 {
public static long MOD = 1000000007;
static int[][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
int[] pre = new int[n];
int[] count = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
dp = new int[n][n];
for (int[] a : dp) {
Arrays.fill(a, -1);
}
for (int i = n - 1; i >= 0; i--) {
pre[i] += (1 - data[i]);
count[i] += data[i];
if (i + 1 < n) {
pre[i] += pre[i + 1];
count[i] += count[i + 1];
}
}
out.println(cal(0, 0, pre, count, data));
out.close();
}
static int cal(int index, int pos, int[] pre, int[] count, int[] data) {
if (index == data.length) {
return 0;
}
if (pos == data.length) {
if(count[index] == 0){
return 0;
}
return data.length * data.length;
}
if (count[index] > pre[pos]) {
return data.length * data.length;
}
if (data[index] == 0) {
return cal(index + 1, pos, pre, count, data);
}
if (data[pos] == 1) {
return cal(index, pos + 1, pre, count, data);
}
if (dp[index][pos] != -1) {
return dp[index][pos];
}
int result = Integer.min(cal(index + 1, pos + 1, pre, count, data) + abs(index - pos), cal(index, pos + 1, pre, count, data));
return dp[index][pos] = result;
}
static int abs(int v) {
return v < 0 ? -v : v;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x;
String y;
public Point(int start, String end) {
this.x = start;
this.y = end;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
671b0a5c8f9e9f25f7ad4c153a6a820f
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer> one=new ArrayList<>();
static ArrayList<Integer> zero=new ArrayList<>();
static long dp[][]= new long[5001][5001];
static long solve(int i,int j){
if (i==one.size())return 0;
if (j==zero.size())return Integer.MAX_VALUE;
if (dp[i][j]!=-1){
return dp[i][j];
}
return dp[i][j]=Math.min(solve(i+1,j+1)+Math.abs(one.get(i)-zero.get(j)),solve(i,j+1));
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
// int t=sc.nextInt();
// while (t-->=1){
int n=sc.nextInt();
int a[]=sc.readArray(n);
for (long i[]:dp){
Arrays.fill(i,-1);
}
for (int i=0;i<n;i++){
if (a[i]==1)one.add(i);
else zero.add(i);
}
Collections.sort(one);
Collections.sort(zero);
System.out.println(solve(0,0));
}
// out.flush();
//------------------------------------if-------------------------------------------------------------------------------------------------------------------------------------------------
//sieve
static void primeSieve(int a[]){
//mark all odd number as prime
for (int i=3;i<a.length;i+=2){
a[i]=1;
}
for (long i=3;i<a.length;i+=2){
//if the number is marked then it is prime
if (a[(int) i]==1){
//mark all muliple of the number as not prime
for (long j=i*i;j<a.length;j+=i){
a[(int)j]=0;
}
}
}
a[2]=1;
a[1]=a[0]=0;
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static String sortString(String s) {
char temp[] = s.toCharArray();
Arrays.sort(temp);
return new String(temp);
}
static class Pair implements Comparable<Pair> {
String a;
int b;
public Pair(String a, int b) {
this.a = a;
this.b = b;
}
// to sort first part
// public int compareTo(Pair other) {
// if (this.a == other.a) return other.b > this.b ? -1 : 1;
// else if (this.a > other.a) return 1;
// else return -1;
// }
public int compareTo(Pair other) {
// if (this.b == other.b) return 0;
if (this.b > other.b) return 1;
else return -1;
}
//sort on the basis of first part only
// public int compareTo(Pair other) {
// if (this.a == other.a) return 0;
// else if (this.a > other.a) return 1;
// else return -1;
// }
}
static int[] frequency(String s){
int fre[]= new int[26];
for (int i=0;i<s.length();i++){
fre[s.charAt(i)-'a']++;
}
return fre;
}
static long LOWERBOUND(long a[],long k){
int s=0,e=a.length-1;
long ans=-1;
while (s<=e){
int mid=(s+e)/2;
if (a[mid]<=k){
ans=mid;
s=mid+1;
}
else {
e=mid-1;
}
}
return ans;
}
static long mod =(long)(1e9+7);
static long mod(long x) {
return ((x % mod + mod) % mod);
}
static long div(long a,long b){
return ((a/b)%mod+mod)%mod;
}
static long add(long x, long y) {
return mod(mod(x) + mod(y));
}
static long mul(long x, long y) {
return mod(mod(x) * mod(y));
}
//Fast Power(logN)
static int fastPower(long a,long n){
int ans=1;
while (n>0){
long lastBit=n&1;
if (lastBit==1){
ans=(int)mul(ans,a);
}
a=(int)mul(a,a);
n>>=1;
}
return ans;
}
static int[] find(int n, int start, int diff) {
int a[] = new int[n];
a[0] = start;
for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff;
return a;
}
static void swap(int a, int b) {
int c = a;
a = b;
b = c;
}
static void printArray(int a[]) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
static boolean sorted(int a[]) {
int n = a.length;
boolean flag = true;
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) flag = false;
}
if (flag) return true;
else return false;
}
public static int findlog(long n) {
if (n == 0)
return 0;
if (n == 1)
return 0;
if (n == 2)
return 1;
double num = Math.log(n);
double den = Math.log(2);
if (den == 0)
return 0;
return (int) (num / den);
}
public static long gcd(long a, long b) {
if (b % a == 0)
return a;
return gcd(b % a, a);
}
public static int gcdInt(int a, int b) {
if (b % a == 0)
return a;
return gcdInt(b % a, a);
}
static void sortReverse(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
// Collections.sort.(l);
Collections.sort(l, Collections.reverseOrder());
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readArrayLong(long n) {
long[] a = new long[(int) n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
59a047ed9cbe1fd4e221d9316d4d972e
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> a1 = new ArrayList<>();
List<Integer> a0 = new ArrayList<>();
for (int i = 0; i < n; i++) {
int now = sc.nextInt();
if (now == 1) {
a1.add(i + 1);
} else {
a0.add(i + 1);
}
}
int[][] dp = new int[a1.size() + 1][a0.size() + 1];
for (int i = 1; i < dp.length; i++) {
dp[i][i] = dp[i - 1][i - 1] + Math.abs(a1.get(i - 1) - a0.get(i - 1));
for (int j = i + 1; j < dp[i].length; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j - 1] + Math.abs(a1.get(i - 1) - a0.get(j - 1)));
}
}
System.out.println(dp[a1.size()][a0.size()]);
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
438edb5cd33253fb9b5baeaad0ae1a49
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
/*
* HI THERE! (:
*
* CREATED BY : NAITIK V
*
* JAI HIND
*
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc=new FastReader();
static long dp[][];
static int mod=1000000007;
static int max;
public static void main(String[] args)
{
PrintWriter out=new PrintWriter(System.out);
//StringBuffer sb=new StringBuffer("");
int ttt=1;
//ttt =i();
outer :while (ttt-- > 0)
{
int n=i();
int A[]=input(n);
dp=new long[n+1][n+1];
for(int i=0;i<=n;i++) {
Arrays.fill(dp[i],-1);
}
ArrayList<Integer> l=new ArrayList<Integer>();
ArrayList<Integer> m=new ArrayList<Integer>();
for(int i=0;i<n;i++) {
if(A[i]==0) {
l.add(i+1);
}
else {
m.add(i+1);
}
}
A=new int[m.size()];
int B[]=new int[l.size()];
for(int i=0;i<l.size();i++) {
B[i]=l.get(i);
}
for(int i=0;i<m.size();i++) {
A[i]=m.get(i);
}
n=m.size();
int o=l.size();
System.out.println(go(A,B,0,0,n,o));
}
//System.out.println(sb.toString());
out.close();
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
//CHECK FOR N=1
//CHECK FOR N=1
}
private static long go(int[] A, int[] B, int i, int j, int n, int m) {
if(i==n)
return 0;
if(j==m)
return Integer.MAX_VALUE;
if(dp[i][j]!=-1)
return dp[i][j];
long op1=go(A, B, i+1, j+1, n, m)+Math.abs(A[i]-B[j]);
long op2=go(A, B, i, j+1, n, m);
return dp[i][j]=Math.min(op1, op2);
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
if(this.x>o.x)
return 1;
else if(this.x<o.x)
return -1;
else {
if(this.y>o.y)
return 1;
else if(this.y<o.y)
return -1;
else
return 0;
}
}
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
cb601b0db13248995683cd4948b9d8b9
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/*long startTime = System.currentTimeMillis(); //获取开始时间
* long endTime = System.currentTimeMillis(); //获取结束时间
* System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间
*/
public class Main{
static final int n=998244353;
public static void main(String[] args){
Read in=new Read(System.in);
int n=in.nextInt();
int [] arr=new int [n];
int k=0;
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
if(arr[i]==1) k++;
}
int [] f=new int [k];
int index=0;
for(int i=0;i<n;i++) {
if(arr[i]==1) f[index++]=i;
}
int [][] dp=new int [k][n];
for(int i=0;i<k;i++)
Arrays.fill(dp[i],1000000000);
for(int i=0;i<n&&k!=0;i++) {
if(arr[i]==0) {
dp[0][i]=Math.min(dp[0][i], (int)Math.abs(i-f[0]));
}
if(i+1<n)
dp[0][i+1]=dp[0][i];
}
for(int i=0;i<k;i++) {
for(int j=0;j<n-1;j++) {
if(dp[i][j]==1000000000) continue;
dp[i][j+1]=Math.min(dp[i][j+1],dp[i][j]);
if(arr[j+1]==0&&i+1<k)
dp[i+1][j+1]=Math.min(dp[i+1][j+1], dp[i][j]+(int)Math.abs(j+1-f[i+1]));
}
}
/*for(int i=0;i<k;i++) {
for(int j=0;j<n;j++) {
System.out.println(i+":"+j+":"+dp[i][j]);
}
}*/
if(k==0) System.out.print(0);
else System.out.print(dp[k-1][n-1]);
}
static class Read {//自定义快读 Read
public BufferedReader reader;
public StringTokenizer tokenizer;
public Read(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
63fc8740d9ed783b13c216f86422b0c6
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.*;
public class Ishu
{
static Scanner scan = new Scanner(System.in);
static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
static void tc() throws Exception
{
int n = scan.nextInt();
int[] a = new int[n];
int one = 0;
int i,j;
for(i=0;i<n;++i)
{
a[i] = scan.nextInt();
one += a[i];
}
int[] pos = new int[one];
one = 0;
for(i=0;i<n;++i)
if(a[i] == 1)
pos[one++] = i;
long[][] dp = new long[one][n];
if(one == 0)
{
output.write("0\n");
output.flush();
return;
}
if(a[0] == 0)
dp[0][0] = pos[0];
else
dp[0][0] = Integer.MAX_VALUE;
for(j=1;j<n;++j)
{
if(a[j] == 1)
{
dp[0][j] = dp[0][j-1];
continue;
}
dp[0][j] = Math.abs(pos[0] - j);
dp[0][j] = Math.min(dp[0][j], dp[0][j-1]);
}
for(i=1;i<one;++i)
{
int cnt = 0;
for(j=0;j<n;++j)
{
if(a[j] == 0)
++cnt;
if(cnt == i + 1)
break;
dp[i][j] = Integer.MAX_VALUE;
}
for(;j<n;++j)
{
if(a[j] == 1)
{
dp[i][j] = dp[i][j-1];
continue;
}
dp[i][j] = Math.abs(pos[i] - j) + dp[i-1][j-1];
dp[i][j] = Math.min(dp[i][j], dp[i][j-1]);
}
}
// for(i=0;i<one;++i)
// {
// for(j=0;j<n;++j)
// output.write(dp[i][j] + " ");
// output.write("\n");
// }
long ans = dp[one-1][n-1];
output.write(ans + "\n");
output.flush();
}
public static void main(String[] args) throws Exception
{
int t = 1;
//t = scan.nextInt();
while(t-- > 0)
tc();
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
9f2e5e4098d25a027e4dd52f0bfd1048
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class codeforcesD{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static long dp[][];
public static List<Integer> list1,list0;
public static void main(String args[]){
FastReader sc=new FastReader();
int n=sc.nextInt();
list1=new ArrayList<>();
list0=new ArrayList<>();
for(int i=0;i<n;i++){
int a=sc.nextInt();
if(a==0){list0.add(i);}
if(a==1){list1.add(i);}
}
dp=new long[list1.size()][list0.size()];
for(int i=0;i<list1.size();i++){
for(int j=0;j<list0.size();j++){
dp[i][j]=-1;
}
}
System.out.println(check(0,0));
}
public static long check(int i,int j){
if(i>=list1.size()){return 0;}
if(j>=list0.size()){return Integer.MAX_VALUE;}
if(dp[i][j]!=-1){return dp[i][j];}
dp[i][j]=Math.min(check(i+1,j+1)+(long)Math.abs(list1.get(i)-list0.get(j)),check(i,j+1));
return dp[i][j];
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
c6b22a02371df3842a2e8bbea3f460ac
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.StringJoiner;
public class D {
private static List<Long> chairs;
private static List<Long> folks;
private static Long[] data;
private static Long[][] cache;
public static void main(String[] args) {
Print print = new Print();
Scan scan = new Scan();
int n = scan.scanInt();
data = scan.scan1dLongArray();
chairs = new ArrayList<>();
folks = new ArrayList<>();
cache = new Long[n][n];
for (int i = 0; i < n; i++) {
if (data[i] == 0) {
chairs.add((long) i);
} else {
folks.add((long) i);
}
}
print.printLine(Long.toString(solve(folks, chairs, 0, 0)));
print.close();
}
private static long solve(List<Long> folks, List<Long> chairs, int i, int j) {
if (i == folks.size()) {
return 0;
}
if (j == chairs.size()) {
return Integer.MAX_VALUE;
}
if (cache[i][j] != null) {
return cache[i][j];
}
return cache[i][j] = Math
.min(Math.abs(folks.get(i) - chairs.get(j)) + solve(folks, chairs, i + 1, j + 1),
solve(folks, chairs, i, j + 1));
}
static class Scan {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan() {
in = System.in;
}
public int scan() {
if (total < 0) {
throw new InputMismatchException();
}
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (IOException ignored) {
}
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) {
n = scan();
}
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
} else {
throw new InputMismatchException();
}
}
return neg * integer;
}
public double scanDouble() {
double doub = 0;
int n = scan();
while (isWhiteSpace(n)) {
n = scan();
}
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n) && n != '.') {
if (n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = scan();
} else {
throw new InputMismatchException();
}
}
if (n == '.') {
n = scan();
double temp = 1;
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = scan();
} else {
throw new InputMismatchException();
}
}
}
return doub * neg;
}
public Integer[] scan1dIntArray() {
String[] s = this.scanString().split(" ");
Integer[] arr = new Integer[s.length];
for (int i = 0; i < s.length; i++) {
arr[i] = Integer.parseInt(s[i]);
}
return arr;
}
public Integer[][] scan2dIntArray(int n, int m) {
Integer[][] arr = new Integer[n][m];
for (int i = 0; i < n; i++) {
String[] s = this.scanString().split(" ");
for (int j = 0; j < m; j++) {
arr[i][j] = Integer.parseInt(s[j]);
}
}
return arr;
}
public String[] scan1dStringArray() {
return this.scanString().split(" ");
}
public String[][] scan2dStringArray(int n, int m) {
String[][] arr = new String[n][m];
for (int i = 0; i < n; i++) {
String[] s = this.scanString().split(" ");
for (int j = 0; j < m; j++) {
arr[i][j] = s[j];
}
}
return arr;
}
public char[] scan1dCharArray() {
return this.scanString().toCharArray();
}
public char[][] scan2dCharArray(int n, int m) {
char[][] arr = new char[n][m];
for (int i = 0; i < n; i++) {
char[] s = this.scanString().toCharArray();
for (int j = 0; j < m; j++) {
arr[i][j] = s[j];
}
}
return arr;
}
public Long[] scan1dLongArray() {
String[] s = this.scanString().split(" ");
Long[] arr = new Long[s.length];
for (int i = 0; i < s.length; i++) {
arr[i] = Long.parseLong(s[i]);
}
return arr;
}
public Long[][] scan2dLongArray(int n, int m) {
Long[][] arr = new Long[n][m];
for (int i = 0; i < n; i++) {
String[] s = this.scanString().split(" ");
for (int j = 0; j < m; j++) {
arr[i][j] = Long.parseLong(s[j]);
}
}
return arr;
}
public String scanString() {
StringBuilder sb = new StringBuilder();
int n = scan();
while (isWhiteSpace(n)) {
n = scan();
}
while (!isWhiteSpace(n)) {
sb.append((char) n);
n = scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
if (n == '\n' || n == '\r' || n == '\t' || n == -1) {
return true;
}
return false;
}
}
static class Print {
private final BufferedWriter bw;
public Print() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(String str) {
try {
bw.append(str);
} catch (IOException ignored) {
}
}
public void printLine(Integer[] arr) {
StringJoiner sj = new StringJoiner(" ");
for (Integer x : arr) {
sj.add(Integer.toString(x));
}
printLine(sj.toString());
}
public void printLine(Integer[][] arr) {
for (Integer[] x : arr) {
StringJoiner sj = new StringJoiner(" ");
for (Integer y : x) {
sj.add(Integer.toString(y));
}
printLine(sj.toString());
}
}
public void printLine(String[] arr) {
StringJoiner sj = new StringJoiner(" ");
for (String x : arr) {
sj.add(x);
}
printLine(sj.toString());
}
public void printLine(String[][] arr) {
for (String[] x : arr) {
StringJoiner sj = new StringJoiner(" ");
for (String y : x) {
sj.add(y);
}
printLine(sj.toString());
}
}
public void printLine(char[] arr) {
StringJoiner sj = new StringJoiner(" ");
for (char x : arr) {
sj.add(Character.toString(x));
}
printLine(sj.toString());
}
public void printLine(char[][] arr) {
for (char[] x : arr) {
StringJoiner sj = new StringJoiner(" ");
for (char y : x) {
sj.add(Character.toString(y));
}
printLine(sj.toString());
}
}
public void printLine(Long[] arr) {
StringJoiner sj = new StringJoiner(" ");
for (Long x : arr) {
sj.add(Long.toString(x));
}
printLine(sj.toString());
}
public void printLine(Long[][] arr) {
for (Long[] x : arr) {
StringJoiner sj = new StringJoiner(" ");
for (Long y : x) {
sj.add(Long.toString(y));
}
printLine(sj.toString());
}
}
public void printLine(String str) {
print(str);
try {
bw.append("\n");
} catch (IOException ignored) {
}
}
public void close() {
try {
bw.close();
} catch (IOException ignored) {
}
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
d57f9e9cd796126538ae3805ed51856a
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.compare;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.util.Arrays.asList;
import static java.util.Collections.max;
import static java.util.Collections.min;
public class Main {
private static final int MOD = (int) (1E9 + 7);
private static final int INF = (int) (1E9);
static FastScanner scanner = new FastScanner(in);
public static void main(String[] args) throws IOException {
// Write your solution here
StringBuilder answer = new StringBuilder();
int t = 1;
// t = parseInt(scanner.nextLine());
while (t-- > 0) {
answer.append(solve()).append("\n");
}
out.println(answer);
}
private static Object solve() throws IOException {
int n = scanner.nextInt();
Integer[] a = new Integer[n];
ArrayList<Integer> one = new ArrayList<>(), zero = new ArrayList<>();
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
if (a[i] == 0) zero.add(i);
else one.add(i);
}
int[][] dp = new int[one.size() + 1][zero.size() + 1]; // minimum cost using i one and j zeros
for (int i = 0; i <= one.size(); i++) {
for (int j = 0; j <= zero.size(); j++) {
dp[i][j] = INF;
}
}
for (int i = 0; i <= zero.size(); i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= one.size(); i++) {
for (int j = 1; j <= zero.size(); j++) {
dp[i][j] = minn(dp[i - 1][j - 1] + Math.abs(one.get(i - 1) - zero.get(j - 1)), dp[i][j-1]);
}
}
return dp[one.size()][zero.size()];
}
private static int maxx(Integer... a) {
return max(asList(a));
}
private static int minn(Integer... a) {
return min(asList(a));
}
private static long maxx(Long... a) {
return max(asList(a));
}
private static long minn(Long... a) {
return min(asList(a));
}
private static int add(int a, int b) {
long res = ((long) (a + MOD) % MOD + (b + MOD) % MOD) % MOD;
return (int) res;
}
private static int mul(int a, int b) {
long res = ((long) a % MOD * b % MOD) % MOD;
return (int) res;
}
private static int pow(int a, int b) {
a %= MOD;
int res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mul(res, a);
a = mul(a, a);
b >>= 1;
}
return res;
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static class Pair implements Comparable<Pair> {
int index, value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
public int compareTo(Pair o) {
if (value != o.value) return compare(value, o.value);
return compare(index, o.index);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return parseInt(next());
}
long nextLong() {
return parseLong(next());
}
double nextDouble() {
return parseDouble(next());
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
| |
PASSED
|
5afdc6d3f250fb698a48530a4f7f7daf
|
train_110.jsonl
|
1621152000
|
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?
|
512 megabytes
|
import javafx.beans.NamedArg;
import java.io.*;
import java.util.Comparator;
import java.util.*;
/**
* @author Yuxuan Wu
*/
public class Main {
public static final int RANGE = 1000000;
static int MAX = Integer.MAX_VALUE;
static int MIN = Integer.MIN_VALUE;
static int MODULO = 1000000007;
static Scanner sc = new Scanner(System.in);
static int multi = 0;
static int maxvalue = 5001 * 5001 + 100;
private static void solve() {
int n = sc.nextInt();
int[][] a = new int[n + 1][2];
int[] cnt = new int[2];
for(int i = 1; i <= n; i++){
int x = sc.nextInt();
cnt[x]++;
a[cnt[x]][x] = i;
}
int[][] dp = new int[cnt[1] + 1][cnt[0] + 1];
for(int i = 0; i <= cnt[1]; i++){
for(int j = 0; j <= cnt[0]; j++){
dp[i][j] = maxvalue;
}
}
dp[0][0] = 0;
for(int i = 0; i <= cnt[1]; i++){
for(int j = i; j <= cnt[0]; j++){
if(j == i && j == 0){
continue;
}
dp[i][j] = Math.min(dp[i][j - 1], i > 0 ? dp[i - 1][j - 1] + Math.abs(a[i][1] - a[j][0]) : maxvalue);
}
}
System.out.print(dp[cnt[1]][cnt[0]]);
}
public static void main(String[] args) {
if(multi == 0){
solve();
}
else {
int T = sc.nextInt();
for(int t = 1; t <= T; ++t){
solve();
}
}
}
/**
* 返回最大公约数
* 时间复杂度 O(Log min(n1, n2))
*/
public static long gcd(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return gcd(n2, n1 % n2);
}
/**
* 返回该数的位数
*/
public static int getDigit(long num){
int ans = 0;
while(num > 0){
num /= 10;
ans++;
}
return ans;
}
/**
* 判断是否为回文串
*/
public static boolean palindrome(String s) {
int n = s.length();
for(int i = 0; i < n; i++) {
if(s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
/**
* 判断是否为完全平方数
*/
public static boolean isSquare(int num) {
double a = 0;
try {
a = Math.sqrt(num);
} catch (Exception e) {
return false;
}
int b = (int) a;
return a - b == 0;
}
public static class Pairs<K, V> implements Comparable<Pairs> {
private K key;
private V value;
public K getKey() { return key; }
public V getValue() { return value; }
public void setKey(K key) {
this.key = key;
}
public void setValue(V value) {
this.value = value;
}
public Pairs(@NamedArg("key") K key, @NamedArg("value") V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return key + " = " + value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pairs<?, ?> pairs = (Pairs<?, ?>) o;
return Objects.equals(key, pairs.key) &&
Objects.equals(value, pairs.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public int compareTo(Pairs o) {
return 0;
}
}
static class CompInt implements Comparator<Pairs>{
@Override
public int compare(Pairs o1, Pairs o2) {
if(o1.key instanceof Integer&&o2.key instanceof Integer){
if((int)o1.key>(int)o2.key){
return 1;
}else{
return -1;
}
}
return 0;
}
}
static class CompLong implements Comparator<Pairs>{
@Override
public int compare(Pairs o1, Pairs o2) {
return Long.compare((long)o1.key, (long)o2.key);
}
}
static class CompDouble implements Comparator<Pairs>{
@Override
public int compare(Pairs o1, Pairs o2) {
if(o1.key instanceof Double && o2.key instanceof Double){
return Double.compare((double) o1.key, (double) o2.key);
}
return 0;
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null) {
return;
}
din.close();
}
}
}
|
Java
|
["7\n1 0 0 1 0 0 1", "6\n1 1 1 0 0 0", "5\n0 0 0 0 0"]
|
2 seconds
|
["3", "9", "0"]
|
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.
|
Java 8
|
standard input
|
[
"dp",
"flows",
"graph matchings",
"greedy"
] |
ff5abd7dfd6234ddaf0ee7d24e02c404
|
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}$$$.
| 1,800 |
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.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.