Codeforces Zuma Solution in Java

import java.io.*;
import java.util.*;
import java.math.*;
public class Zuma
{

public static void main(String[] args)
{
MyS sc=new MyS();
int n=sc.nextInt();
int c[]=new int[n];
int i,j;
for(i=0;i<n;i++)
c[i]=sc.nextInt();
int d[][]=new int[n][n];
for(i=n-1;i>=0;i--)
{
for(j=n-1;j>=0;j--)
{
if(i>j)
{
d[i][j]=0;
}
else if(i==j)
{
d[i][j]=1;
}
else
{
d[i][j]=1+d[i+1][j];
for(int k=i+2;k<=j;k++){
if(c[i]==c[k]){


int v=d[i+1][k-1];
if(k!=j)
v+=d[k+1][j];
d[i][j]=Math.min(d[i][j],v);

}

}
if(c[i]==c[i+1]){
int v=1;
if((i+1)!=j)
v+=d[i+2][j];
d[i][j]=Math.min(d[i][j],v);

}
}
}
}

System.out.println(d[0][n-1]);

}

}
class MyS
{
BufferedReader br;
StringTokenizer st;
MyS()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{

while(st==null || !st.hasMoreTokens())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(Exception 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(Exception e)
{
e.printStackTrace();
}
return str;

}
}

Comments

Popular Posts