Sunday, January 29, 2012
My Facebook Hacker Cup 2012 Round 1 - Checkpoint answer (Java)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class C {
static int nCrMax=10000000;
static long _nCr[]=new long[nCrMax+1];
static long _tmpnCr[]=new long[nCrMax+1];
static int _n[]=new int[nCrMax+1];
static int _r[]=new int[nCrMax+1];
private static void init()
{
for(int i=1;i<=nCrMax;i++)
{
_n[i]=i;
_r[i]=1;
}
_n[0]=0;_r[0]=0; //Not use
_nCr[0]=1;
_nCr[1]=1;
int thisRowEnd=0,r=0;
for(int n=2;n<=nCrMax;n++)
{
for(r=1;r<=((int)(n/2));r++)
{
if(r==((int)(n/2))&&n%2==0)
_tmpnCr[r]=(_nCr[r-1]*2);
else
_tmpnCr[r]=(_nCr[r]+_nCr[(r-1)]);
if(_tmpnCr[r]>nCrMax)
{
break;
}
}
thisRowEnd=r-1;
for(r=1;r<=thisRowEnd;r++)
{
_nCr[r]=_tmpnCr[r];
int ncr=(int)_nCr[r];
if((_n[ncr]+_r[ncr])>(n+r))
{
_n[ncr]=n;
_r[ncr]=r;
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
init();
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int T = in.nextInt();
for (int i = 0; i < T; i++) {
String s = new C().solve(in,i+1);
out.println(s);
System.out.println(s);
}
out.close();
}
synchronized private String solve(Scanner in, int caseid) {
int s = in.nextInt();
int i;
int res=Integer.MAX_VALUE;
if(s==1)
{
res=_n[1]+_n[1];
}
else
{
for(i=1;i*i<=s;i++)
{
if(s%i==0)
{
int s1=i;
int s2=s/i;
if(res>(_n[s1]+_n[s2]))
res=_n[s1]+_n[s2];
}
}
}
return "Case #"+caseid+": "+res;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment