Monday, 24 February 2014

UVA Problem ID 10924 (Prime Words)

UVA Problem ID 10924 (Prime Words)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main{
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		while((input=br.readLine())!=null) 
		{
			int sum=0;
			for (int i = 0; i < input.length(); i++) {
				if(input.charAt(i)>=97 && input.charAt(i)<=122)
					sum+=input.charAt(i)-96;
				else if(input.charAt(i)>=65 && input.charAt(i)<=90)
					sum+=input.charAt(i)-38;
			}
			if(isPrime(sum))
				sb.append("It is a prime word.\n");
			else
				sb.append("It is not a prime word.\n");
		}
		System.out.print(sb);
	}
	public static boolean isPrime(int number)
	{
		if(number!=2  && number%2==0)
			return false;
		for (int i =3; i <= Math.ceil(Math.sqrt(number)); i=i+2) {
			if(number%i==0)
				return false;
		}
		return true;
	}
}

UVA Problem ID 10946 (You want what filled?)

UVA Problem ID 10946 (You want what filled?)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	static char grid[][];
	static boolean wasVisited[][];
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int testcase=0;
		while((input=br.readLine())!=null) 
		{
			String s[]=input.split(" +");
			int row=Integer.parseInt(s[0]);
			int column=Integer.parseInt(s[1]);
			if(row==0 && column==0)
				break;
			testcase++;
			grid=new char[row][column];
			wasVisited=new boolean[row][column];
			for (int i = 0; i < row; i++) {
				input=br.readLine().trim();
				for (int j = 0; j rowlimit || column>columnlimit || row<0 || column<0 || wasVisited[row][column]==true)
			return 0;
		if(grid[row][column]==c)
		{
			count++;
			grid[row][column]='.';
			wasVisited[row][column]=true;
			count+=floodfill(row-1,column,c,rowlimit,columnlimit);
			count+=floodfill(row,column-1,c,rowlimit,columnlimit);
			count+=floodfill(row,column+1,c,rowlimit,columnlimit);
			count+=floodfill(row+1,column,c,rowlimit,columnlimit);
			return count;
		}
		return 0;
	}
}
class Hole implements Comparable
{
	char name;
	int count;
	public Hole(char n,int c)
	{
		name=n;
		count=c;
	}
	
	@Override
	public int compareTo(Hole h1) {
		if(this.count>h1.count)
			return -1;
		else if(this.count 

UVA Problem ID 10336 (Rank the Languages)

UVA Problem ID 10336 (Rank the Languages)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	static char grid[][];
	static boolean wasVisited[][];
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int testcase=Integer.parseInt(br.readLine());
		for (int t1 = 0; t1 rowlimit || column>columnlimit || row<0 || column<0 || wasVisited[row][column]==true)
			return ;
		if(grid[row][column]==c)
		{
			grid[row][column]='.';
			wasVisited[row][column]=true;
		
		
		floodfill(row-1,column,c,rowlimit,columnlimit);
		floodfill(row,column-1,c,rowlimit,columnlimit);
		floodfill(row,column+1,c,rowlimit,columnlimit);
		floodfill(row+1,column,c,rowlimit,columnlimit);
		}
		
	}
}
class Token implements Comparable
{
	char name;
	int count;
	public Token(char n,int c)
	{
		name=n;
		count=c;
	}
	
	@Override
	public int compareTo(Token t1) {
		if(this.count>t1.count)
			return -1;
		else 
			return 1;
	}
}

UVA Problem ID 784 (Maze Exploration)

UVA Problem ID 784 (Maze Exploration)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	static char grid[][]=new char[30][];
	static boolean wasVisited[][]=new boolean[30][];
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int testases=Integer.parseInt(br.readLine());
		for (int t1 = 0; t1 < testases; t1++) 
		{
			input=br.readLine();
			int t=0;
			do {
				grid[t]=new char[input.length()];
				wasVisited[t]=new boolean[input.length()];
				for (int j = 0; j rowlimit || column>columnlimit || row<0 || column<0 )
			return;
		if(grid[row][column]=='X' || wasVisited[row][column]==true)
			return;
			
		if(grid[row][column]==' ' || grid[row][column]=='*')
		{
			grid[row][column]='#';
			wasVisited[row][column]=true;
		}
		floodfill(row-1,column,rowlimit,grid[row-1].length-1);
		floodfill(row,column-1,rowlimit,grid[row].length-1);
		floodfill(row,column+1,rowlimit,grid[row].length-1);
		floodfill(row+1,column,rowlimit,grid[row+1].length-1);
	}
}

UVA Problem ID 871 (Counting Cells in a Blob)

UVA Problem ID 871 (Counting Cells in a Blob)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	static int grid[][];
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int t = 0; t < testcases; t++) 
		{
			if(t>0)
				sb.append("\n");
			br.readLine();
			input=br.readLine();
			int dimension=input.length();
			grid=new int[dimension][dimension];
			for (int j = 0; j < dimension; j++) {
				grid[0][j]=input.charAt(j)-48;
			}
			for (int i = 1; i < dimension; i++) {
				input=br.readLine();
				for (int j = 0; j < dimension; j++) {
					grid[i][j]=input.charAt(j)-48;
				}
			}
			
			int largest=0;
			for (int i = 0; i < dimension; i++) {
				for (int j = 0; j largest)
							largest=count;
					}
				}
			}
			sb.append(largest+"\n");
		}
		System.out.print(sb);

	}
	public static int floodfill(int row,int column,int rowlimit,int columnlimit)
	{
		if(grid[row][column]!=1)
			return 0;
		int count=1;
		
		
		grid[row][column]=0;
		if(row-1>=0)
		{
			count+=floodfill(row-1, column, rowlimit, columnlimit);
			if(column-1>=0)
				count+=floodfill(row-1, column-1, rowlimit, columnlimit);
			if(column+1<=columnlimit)
				count+=floodfill(row-1, column+1, rowlimit, columnlimit);
		}
		if(row+1<=rowlimit)
		{
			count+=floodfill(row+1, column, rowlimit, columnlimit);
			if(column-1>=0)
				count+=floodfill(row+1, column-1, rowlimit, columnlimit);
			if(column+1<=columnlimit)
				count+=floodfill(row+1, column+1, rowlimit, columnlimit);
		}
		if(column-1>=0)
			count+=floodfill(row, column-1, rowlimit, columnlimit);
		if(column+1<=columnlimit)
			count+=floodfill(row, column+1, rowlimit, columnlimit);
		return count;
	}

}

UVA Problem ID 11244 (Counting Stars)

UVA Problem ID 11244 (Counting Stars)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	static char image[][];
	public static void main(String[] args) throws IOException {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		while((input=br.readLine())!=null)
		{
			String s[]=input.split(" +");
			int row=Integer.parseInt(s[0]);
			int column=Integer.parseInt(s[1]);
			if(row==0 && column==0)
				break;
			image=new char[row][column];
			for (int i = 0; i < row; i++) {
				input=br.readLine();
				for (int j = 0; j < column; j++) {
					image[i][j]=input.charAt(j);
				}
			}
			int no_of_stars=0;
			for (int i = 0; i < row; i++) {
				for (int j = 0; j =0)
		{
			count+=floodfill(row-1, column, rowlimit, columnlimit);
			if(column-1>=0)
				count+=floodfill(row-1, column-1, rowlimit, columnlimit);
			if(column+1<=columnlimit)
				count+=floodfill(row-1, column+1, rowlimit, columnlimit);
		}
		if(row+1<=rowlimit)
		{
			count+=floodfill(row+1, column, rowlimit, columnlimit);
			if(column-1>=0)
				count+=floodfill(row+1, column-1, rowlimit, columnlimit);
			if(column+1<=columnlimit)
				count+=floodfill(row+1, column+1, rowlimit, columnlimit);
		}
		if(column-1>=0)
			count+=floodfill(row, column-1, rowlimit, columnlimit);
		if(column+1<=columnlimit)
			count+=floodfill(row, column+1, rowlimit, columnlimit);
		return count;
	}

}

UVA Problem ID 11470 (Square Sums)

UVA Problem ID 11470 (Square Sums)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	static int square[][];
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		int testno=0;
		StringBuilder sb=new StringBuilder(10000);
		while((input=br.readLine())!=null)
		{
			
			int dimension=Integer.parseInt(input);
			if(dimension==0)
				break;
			testno++;
			square=new int[dimension][dimension];
			for (int i = 0; i < dimension; i++) {
				String s[]=br.readLine().split(" +");
				for (int j = 0; j < dimension; j++) {
					square[i][j]=Integer.parseInt(s[j]);
				}
			}
			sb.append("Case "+testno+": ");
			for (int i = 0; i < dimension/2; i++) {
				int count=0;
				count +=sumsquare(i,i+1,false,dimension-i-1);
				count +=sumsquare(i,i,true,dimension-i);
				count +=sumsquare(dimension-i-1,i+1,false,dimension-i-1);
				count +=sumsquare(i,dimension-i-1,true,dimension-i);
				if(i==0)
					sb.append(count);
				else
					sb.append(" "+count);
			}
			if(dimension % 2!=0 && dimension/2==0)
				sb.append(square[(int) Math.floor(dimension / 2.0)][(int) Math.floor(dimension / 2.0)]);
			else if(dimension % 2!=0)
				sb.append(" "+square[(int) Math.floor(dimension / 2.0)][(int) Math.floor(dimension / 2.0)]);
			sb.append("\n");
		}
		System.out.print(sb);
	}
	public static int sumsquare(int i,int j,boolean isrowchange,int dimension)
	{
		int count=0;
		
		if(isrowchange)
		{
			for (int k = i; k < dimension; k++) {
				count+=square[k][j];
			}
		}
		else
		{
			for (int k = j; k < dimension; k++) {
				count+=square[i][k];
			}
		}
		return count;
	}
}

UVA Problem ID 11078 (Open Credit System)

UVA Problem ID 11078 (Open Credit System)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int t = 0; t < testcases;t++) {
			int n=Integer.parseInt(br.readLine());
			int score[]=new int[n];
			int maxdiff=-99999999,max=-99999999;
			for (int i = 0; i < n; i++) {
				score[i]=Integer.parseInt(br.readLine().trim());
			}
			for (int j =0; j max)
					max=score[j];
				if(max-score[j+1]>maxdiff)
					maxdiff=max-score[j+1];
			}
			sb.append(maxdiff+"\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 10976 (Fractions Again)

UVA Problem ID 10976 (Fractions Again)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		
		StringBuilder sb1=new StringBuilder(1000);
		while((input=br.readLine())!=null)
		{
			StringBuilder sb=new StringBuilder(1000);
			int k=Integer.parseInt(input);
			int count=0;
			for (int i = k+1; i <= k*2; i++) {
				
				if((i*k)%(i-k)==0)
				{
					count++;
					sb.append("1/"+k+" = 1/"+((k*i)/(i-k))+" + 1/"+i+"\n");				
				}
			}
			sb1.append(count+"\n"+sb);
		}
		System.out.print(sb1);
	}
}

UVA Problem ID 11364 (Parking)

UVA Problem ID 11364 (Parking)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine().trim());
		for(int i=0;imax)
				{
					max=Integer.parseInt(s[j]);
				}
				if(Integer.parseInt(s[j])

UVA Problem ID 256 (Quirksome Squares)

UVA Problem ID 256 (Quirksome Squares)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		while((input=br.readLine())!=null)
		{
			int lowerbound=0;
			int upperbound=0;
			int divider=10;
			switch (Integer.parseInt(input)) {
				case 2:
				{
					lowerbound=00;
					upperbound=99;
					divider=10;
					break;
				}
				case 4:
				{
					lowerbound=0000;
					upperbound=9999;
					divider=100;
					break;
				}
				case 6:
				{
					lowerbound=000000;
					upperbound=999999;
					divider=1000;
					break;
				}
				case 8:
				{
					lowerbound=00000000;
					upperbound=99999999;
					divider=10000;
					break;
				}
			}
			for (int i = lowerbound; i <= upperbound; i++) {
				int a=i/divider;
				int b=i-a*divider;
				if((a+b)*(a+b)==i)
				{
					System.out.format("%0"+Integer.parseInt(input)+"d\n",i);
				}
			}
		}
	}
}

UVA Problem ID 12289 (One-Two-Three)

UVA Problem ID 12289 (One-Two-Three)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine().trim());
		for(int i=0;i

UVA Problem ID 12577 (Hajj-e-Akbar)

UVA Problem ID 12577 (Hajj-e-Akbar)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int testcase=0;
		while((input=br.readLine())!=null)
		{
			if(input.trim().equals("*"))
				break;
			testcase++;
			if(input.trim().equals("Hajj"))
				sb.append("Case "+testcase+": Hajj-e-Akbar\n");
			else 
				sb.append("Case "+testcase+": Hajj-e-Asghar\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 12403 (Save Setu)

UVA Problem ID 12403 (Save Setu)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int no_of_operations=Integer.parseInt(br.readLine().trim());
		int money=0;
		for(int i=0;i

UVA Problem ID 12372 (Packing for Holiday)

UVA Problem ID 12372 (Packing for Holiday)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine().trim());
		for(int i=0;i

UVA Problem ID 12279 (Emoogle Balance)

UVA Problem ID 12279 (Emoogle Balance)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int testcase=0;
		while((input=br.readLine())!=null)
		{
			if(Integer.parseInt(input.trim())==0)
				break;
			testcase++;
			String s[]=br.readLine().split(" +");
			int reason=0;
			int party=0;
			for (int i = 0; i < Integer.parseInt(input.trim()); i++) {
				if(Integer.parseInt(s[i])>0)
					reason++;
				else 
					party++;
			}
			sb.append("Case "+testcase+": "+(reason-party)+"\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 12250 (Language Detection)

UVA Problem ID 12250 (Language Detection)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int testcase=0;
		while((input=br.readLine())!=null)
		{
			if(input.equals("#"))
				break;
			testcase++;
			switch (input) {
				case "HELLO":
				{
					sb.append("Case "+testcase+": ENGLISH\n");
					break;
				}
				case "HOLA":
				{
					sb.append("Case "+testcase+": SPANISH\n");
					break;
				}
				case "HALLO":
				{
					sb.append("Case "+testcase+": GERMAN\n");
					break;
				}
				case "BONJOUR":
				{
					sb.append("Case "+testcase+": FRENCH\n");
					break;
				}
				case "CIAO":
				{
					sb.append("Case "+testcase+": ITALIAN\n");
					break;
				}
				case "ZDRAVSTVUJTE":
				{
					sb.append("Case "+testcase+": RUSSIAN\n");
					break;
				}
				default:
				{
					sb.append("Case "+testcase+": UNKNOWN\n");
					break;
				}
			}
		}
		System.out.print(sb);
	}
}

UVA Problem ID 11172 (Relational Operators)

UVA Problem ID 11172 (Relational Operators)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine().trim());
		for(int i=0;ib)
				sb.append(">\n");
			else if(a

UVA Problem ID 1124 (Celebrity jeopardy)

UVA Problem ID 1124 (Celebrity jeopardy)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		while((input=br.readLine())!=null)
		{
			sb.append(input+"\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 572 (Oil Deposits)

UVA Problem ID 572 (Oil Deposits)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		while((input=br.readLine())!=null)
		{
			String s[]=input.split(" +");
			int m=Integer.parseInt(s[0]);
			int n=Integer.parseInt(s[1]);
			if(m==0)
				break;
			char grid[][]=new char[m][n];
			
			for (int i = 0; i < m; i++) {
				input=br.readLine();
				for (int j = 0; j < n; j++) {
					grid[i][j]=input.charAt(j);
				}	
			}
			int no_of_oilDeposits=0;
			for(int i=0;i=0)
		{
			if(column-1>=0 && grid[row-1][column-1]=='@')
				floodfill(grid,row-1, column-1,rowlimit,columnlimit);
			if(column+1=0 && grid[row+1][column-1]=='@')
				floodfill(grid,row+1, column-1,rowlimit,columnlimit);
			if(column+1=0 && grid[row][column-1]=='@')
			floodfill(grid,row, column-1,rowlimit,columnlimit);
		if(column+1

UVA Problem ID 352 (Seasonal War)

UVA Problem ID 352 (Seasonal War)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		int imageNo=0;
		while((input=br.readLine())!=null)
		{
			imageNo++;
			int dimention=Integer.parseInt(input.trim());
			
			char image[][]=new char[dimention][dimention];
			
			for (int i = 0; i < dimention; i++) {
				input=br.readLine();
				for (int j = 0; j < dimention; j++) {
					image[i][j]=input.charAt(j);
				}	
			}
			int no_of_eagle=0;
			for(int i=0;i=0)
		{
			if(column-1>=0 && image[row-1][column-1]=='1')
				floodfill(image,row-1, column-1,dimention);
			if(column+1=0 && image[row+1][column-1]=='1')
				floodfill(image,row+1, column-1,dimention);
			if(column+1=0 && image[row][column-1]=='1')
			floodfill(image,row, column-1,dimention);
		if(column+1

UVA Problem ID 442 (Matrix Chain Multiplication)

UVA Problem ID 442 (Matrix Chain Multiplication)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int no_of_matrices=Integer.parseInt(br.readLine());
		Matrix matrices[]=new Matrix[26];
		for (int i = 0; i  st=new Stack();
			int totalcost=0;
			for (int i = 0; i < input.length(); i++) {
				if(input.charAt(i)=='(')
				{
					//do nothing
				}
				else if(input.charAt(i)==')')
				{
					
					Matrix b=(Matrix) st.pop();
					Matrix a=(Matrix) st.pop();

					if(a.column!=b.row)
					{
						sb.append("error\n");
						flag=false;
						break;
					}
					else
					{
						totalcost+=a.row*a.column*b.column;
						st.push(new Matrix('t',a.row,b.column));		
					}
				}
				else
				{
					st.push(matrices[input.charAt(i)-65]);
				}
			}
			if(st.size()>2)
			{
				sb.append("error\n");
				flag=false;
			}
			else if(!st.isEmpty() && st.size()==2)
			{
				
				Matrix b=(Matrix) st.pop();
				Matrix a=(Matrix) st.pop();	
				if(a.column!=b.row)
				{
					sb.append("error\n");
					flag=false;
				}
				else
				{
					totalcost+=a.row*a.column*b.column;				
				}
			}
			if(flag)
				sb.append(totalcost+"\n");
		}
		System.out.print(sb);
	}
}
class Matrix
{
	public int row;
	public int column;
	public char name;
	
	public Matrix(char name,int row,int column)
	{
		this.name=name;
		this.row=row;
		this.column=column;
	}
}

UVA Problem ID 1237 (Halloween Treats)

UVA Problem ID 1237 (Halloween Treats)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int i = 0; i 0)
				sb.append("\n");
			int d=Integer.parseInt(br.readLine().trim());
			String name[]=new String[d];
			int lowestprice[]=new int[d];
			int highestprice[]=new int[d];
			for(int j=0;j=lowestprice[t] && queryvalue<=highestprice[t])
					{
						index=t;
						count++;
					}
				}
				if(count==1)
					sb.append(name[index]+"\n");
				else
					sb.append("UNDETERMINED\n");
			}
		}
		System.out.print(sb);
	}
}

UVA Problem ID 927 (Integer Sequences from Addition of Terms)

UVA Problem ID 927 (Integer Sequences from Addition of Terms)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int i = 0; i =k)
				{
					for (int t = 0; t < coefficients.length; t++) {
						ans+=coefficients[t]*Math.pow(j, t);
					}
					break;
				}
			}
			sb.append(ans+"\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 294 (Divisors)

UVA Problem ID 294 (Divisors)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int i = 0; i 

UVA Problem ID 11130 (Billiard bounces)

UVA Problem ID 11130 (Billiard bounces)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		while(true)
		{
			String s1[]=br.readLine().split(" +");
			int a=Integer.parseInt(s1[0]);
			int b=Integer.parseInt(s1[1]);
			int v=Integer.parseInt(s1[2]);
			int A=Integer.parseInt(s1[3]);
			int s=Integer.parseInt(s1[4]);
			if(a==0 && b==0 && v==0 && A==0 && s==0 )
				break;
			int horizontaldistance=(int) ((a+v*Math.cos(A*Math.PI/180)*s)/(a*2));
			int verticaldistance=(int) ((b+v*Math.sin(A*Math.PI/180)*s)/(b*2));

			sb.append(horizontaldistance);
			sb.append(" "+verticaldistance+"\n");

		}
		System.out.print(sb);
	}

}

UVA Problem ID 11313 (Gourmet Games)

UVA Problem ID 11313 (Gourmet Games)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int i = 0; i =m)
			{
				total_shows+=left/m;
				left=left/m+left%m;
			}
			if(left==1)
				sb.append(total_shows+"\n");
			else
				sb.append("cannot do this\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 11723 (Numbering Roads)

UVA Problem ID 11723 (Numbering Roads)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcase=0;
		while(true)
		{
			testcase++;
			String s[]=br.readLine().split(" +");
			int R=Integer.parseInt(s[0]);
			int N=Integer.parseInt(s[1]);
			if(R==0 && N==0)
				break;
			int a=R-N;
			int ans;
			if(a%N==0 || R26)
				sb.append("Case "+testcase+": impossible\n");
			else
				sb.append("Case "+testcase+": "+ans+"\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 11805 (Bafana Bafana)

UVA Problem ID 11805 (Bafana Bafana)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int testcases=Integer.parseInt(br.readLine());
		for (int i = 0; i 

UVA Problem ID 10346 (Peter's Smokes)

UVA Problem ID 10346 (Peter's Smokes)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		
		while((input=br.readLine())!=null)
		{
			String s[]=input.split(" +");
			int n=Integer.parseInt(s[0]);
			int k=Integer.parseInt(s[1]);
			int total_cigarettes=n;
			int butts=n;
			while(butts>=k)
			{
				total_cigarettes+=butts/k;
				butts=butts/k+butts%k;
			}
			sb.append(total_cigarettes+"\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 10219 (Find the Ways! )

UVA Problem ID 10219 (Find the Ways! )
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(10000);
		String input;
		while((input=br.readLine())!=null)
		{
			String numbers[]=input.split(" +");
			int n=Integer.parseInt(numbers[0]);
			int r=Integer.parseInt(numbers[1]);
			sb.append(factorial(new BigInteger(n+""),1,r).divide(factorial(new BigInteger(r+""))).toString().length()+"\n");
		}
		System.out.print(sb);
	}
	public static BigInteger factorial(BigInteger n)
	{
		if(n.intValue()==0 || n.intValue()==1)
			return BigInteger.ONE;
		else
		{
			return n.multiply(factorial(n.subtract(BigInteger.ONE)));
		}
	}
	public static BigInteger factorial(BigInteger n,int count,int limit)
	{
		if(n.intValue()==0 || n.intValue()==1)
			return BigInteger.ONE;
		else
		{
			if(count

UVA Problem ID 10303 (How Many Trees)

UVA Problem ID 10303 (How Many Trees)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  StringBuilder sb=new StringBuilder(10000);
  String input;
  while((input=br.readLine())!=null)
  {
   int n=Integer.parseInt(input.trim());
   sb.append(factorial(new BigInteger((2*n)+"")).divide(factorial(new BigInteger(n+"")).multiply(factorial(new BigInteger((n+1)+""))))+"\n");
  }
  System.out.print(sb);
 }
 public static BigInteger factorial(BigInteger n)
 {
  if(n.intValue()==0 || n.intValue()==1)
   return BigInteger.ONE;
  else
  {
   return n.multiply(factorial(n.subtract(BigInteger.ONE)));
  }
 }
}

UVA Problem ID 10220 (I Love Big Numbers!)

UVA Problem ID 10220 (I Love Big Numbers!)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  StringBuilder sb=new StringBuilder(10000);
  String input;
  while((input=br.readLine())!=null)
  {
   int n=Integer.parseInt(input.trim());
   String fac=factorial(new BigInteger(n+"")).toString();
   
   int sum=0;
   for (int i = 0; i < fac.length(); i++) {
    sum=sum+fac.charAt(i)-48;
   }
   sb.append(sum+"\n");
  }
  System.out.print(sb);
 }
 public static BigInteger factorial(BigInteger n)
 {
  if(n.intValue()==0 || n.intValue()==1)
   return BigInteger.ONE;
  else
  {
   return n.multiply(factorial(n.subtract(BigInteger.ONE)));
  }
 }
}

UVA Problem ID 10007 (Count the Trees)

UVA Problem ID 10007 (Count the Trees)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  StringBuilder sb=new StringBuilder(10000);
  
  while(true)
  {
   int n=Integer.parseInt(br.readLine().trim());
   if(n==0)
    break;
   sb.append(factorial(new BigInteger((2*n)+"")).divide(factorial(new BigInteger((n+1)+"")))+"\n");
  }
  System.out.print(sb);
 }
 public static BigInteger factorial(BigInteger n)
 {
  if(n.intValue()==0 || n.intValue()==1)
   return BigInteger.ONE;
  else
  {
   return n.multiply(factorial(n.subtract(BigInteger.ONE)));
  }
 }
}

UVA Problem ID 10334 (Ray Through Glasses)

UVA Problem ID 10334 (Ray Through Glasses)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(10000);
  
  while((input=br.readLine())!=null)
  {
   BigInteger A[][]={{new BigInteger("1"),new BigInteger("1")},{new BigInteger("1"),new BigInteger("0")}};
   
   sb.append(matrixpower(A,Integer.parseInt(input)+2)[1][0]+"\n");
  }
  System.out.print(sb);
 }
 public static BigInteger[][] matrixmultiplication(BigInteger[][] A,BigInteger[][] B)
 {
  BigInteger resultantmatrix[][]=new BigInteger[2][2];
  resultantmatrix[0][0] =  A[0][0].multiply(B[0][0]).add(A[0][1].multiply(B[1][0]));
  resultantmatrix[0][1] =  A[0][0].multiply(B[0][1]).add(A[0][1].multiply(B[1][1]));
  resultantmatrix[1][0] =  A[1][0].multiply(B[0][0]).add(A[1][1].multiply(B[1][0]));
  resultantmatrix[1][1] =  A[1][0].multiply(B[0][1]).add(A[1][1].multiply(B[1][1]));
  
  return resultantmatrix;
 }
 public static BigInteger[][] matrixpower(BigInteger[][] A,int power)
 {
  if(power==0)
  {
   BigInteger matrixA[][]={{new BigInteger("1"),new BigInteger("0")},{new BigInteger("0"),new BigInteger("1")}};
   return matrixA;
  }
  
  else if(power % 2==0)
  {
   BigInteger C[][]=matrixpower(A, power/2);
   return matrixmultiplication(C,C);
  }
  else
  {
   return matrixmultiplication(A,matrixpower(A, power-1));
  }
 }
}

UVA Problem ID 495 (Fibonacci Freeze)

UVA Problem ID 495 (Fibonacci Freeze)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(10000);
  
  while((input=br.readLine())!=null)
  {
   BigInteger A[][]={{new BigInteger("1"),new BigInteger("1")},{new BigInteger("1"),new BigInteger("0")}};
   
   sb.append("The Fibonacci number for "+input+" is "+matrixpower(A,Integer.parseInt(input))[1][0]+"\n");
  }
  System.out.print(sb);
 }
 public static BigInteger[][] matrixmultiplication(BigInteger[][] A,BigInteger[][] B)
 {
  BigInteger resultantmatrix[][]=new BigInteger[2][2];
  resultantmatrix[0][0] =  A[0][0].multiply(B[0][0]).add(A[0][1].multiply(B[1][0]));
  resultantmatrix[0][1] =  A[0][0].multiply(B[0][1]).add(A[0][1].multiply(B[1][1]));
  resultantmatrix[1][0] =  A[1][0].multiply(B[0][0]).add(A[1][1].multiply(B[1][0]));
  resultantmatrix[1][1] =  A[1][0].multiply(B[0][1]).add(A[1][1].multiply(B[1][1]));
  
  return resultantmatrix;
 }
 public static BigInteger[][] matrixpower(BigInteger[][] A,int power)
 {
  if(power==0)
  {
   BigInteger matrixA[][]={{new BigInteger("1"),new BigInteger("0")},{new BigInteger("0"),new BigInteger("1")}};
   return matrixA;
  }
  
  else if(power % 2==0)
  {
   BigInteger C[][]=matrixpower(A, power/2);
   return matrixmultiplication(C,C);
  }
  else
  {
   return matrixmultiplication(A,matrixpower(A, power-1));
  }
 }
}

UVA Problem ID 10579 (Fibonacci Numbers)

UVA Problem ID 10579 (Fibonacci Numbers)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(10000);
  
  while((input=br.readLine())!=null)
  {
   BigInteger A[][]={{new BigInteger("1"),new BigInteger("1")},{new BigInteger("1"),new BigInteger("0")}};
   
   sb.append(matrixpower(A,Integer.parseInt(input))[1][0]+"\n");
  }
  System.out.print(sb);
 }
 public static BigInteger[][] matrixmultiplication(BigInteger[][] A,BigInteger[][] B)
 {
  BigInteger resultantmatrix[][]=new BigInteger[2][2];
  resultantmatrix[0][0] =  A[0][0].multiply(B[0][0]).add(A[0][1].multiply(B[1][0]));
  resultantmatrix[0][1] =  A[0][0].multiply(B[0][1]).add(A[0][1].multiply(B[1][1]));
  resultantmatrix[1][0] =  A[1][0].multiply(B[0][0]).add(A[1][1].multiply(B[1][0]));
  resultantmatrix[1][1] =  A[1][0].multiply(B[0][1]).add(A[1][1].multiply(B[1][1]));
  
  return resultantmatrix;
 }
 public static BigInteger[][] matrixpower(BigInteger[][] A,int power)
 {
  if(power==0)
  {
   BigInteger matrixA[][]={{new BigInteger("1"),new BigInteger("0")},{new BigInteger("0"),new BigInteger("1")}};
   return matrixA;
  }
  
  else if(power % 2==0)
  {
   BigInteger C[][]=matrixpower(A, power/2);
   return matrixmultiplication(C,C);
  }
  else
  {
   return matrixmultiplication(A,matrixpower(A, power-1));
  }
 }
}

UVA Problem ID 389 (Basically Speaking)

UVA Problem ID 389 (Basically Speaking)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(1000);
  
  while((input=br.readLine())!=null)
  {
   String numbers[]=input.trim().split(" +");
   BigInteger no=new BigInteger(numbers[0],Integer.parseInt(numbers[1]));
   String ans=no.toString(Integer.parseInt(numbers[2]));
   if(ans.length()>7)
    sb.append("  ERROR\n");
   else
   {
    while(ans.length()!=7)
     ans=" "+ans;
    sb.append(ans.toUpperCase()+"\n");
   }   
  }
  System.out.print(sb);
 }
}

UVA Problem ID 374 (Big Mod)

UVA Problem ID 374 (Big Mod)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(1000);
  
  while((input=br.readLine())!=null)
  {
   if(input.trim().equals(""))
    input=br.readLine();
   long B=Long.parseLong(input.trim());
   long P=Long.parseLong(br.readLine().trim());
   long M=Long.parseLong(br.readLine().trim());
   sb.append(bigmod(B,P,M)+"\n");
   
  }
  System.out.print(sb);
 }
 public static long bigmod(long b,long p,long m)
 {
  if(p==0)
   return 1;
  else if(p%2==0)
  {
   long temp=bigmod(b,p/2,m);
   return ((temp % m)*(temp % m)) % m;
  }
  else
   return ((b % m)*(bigmod(b,p-1,m) % m)) % m;
     
 }
}

UVA Problem ID 10229 (Modular Fibonacci)

UVA Problem ID 10229 (Modular Fibonacci)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(1000);
  
  while((input=br.readLine())!=null)
  {
   String numbers[]=input.trim().split(" +");
   long matrixA[][]={{1,1},{1,0}};
   long ans=matrixpowerMod(matrixA,Integer.parseInt(numbers[0]),(int) Math.pow(2,Integer.parseInt(numbers[1])))[0][1];
   sb.append(ans+"\n");
  }
  System.out.print(sb);
 }
 public static long[][] matrixmultiplication(long[][] A,long[][] B,int mod)
 {
  long resultantmatrix[][]=new long[2][2];
  resultantmatrix[0][0] =  (A[0][0]*B[0][0] + A[0][1]*B[1][0]) % mod;
  resultantmatrix[0][1] =  (A[0][0]*B[0][1] + A[0][1]*B[1][1]) % mod;
  resultantmatrix[1][0] =  (A[1][0]*B[0][0] + A[1][1]*B[1][0] )% mod;
  resultantmatrix[1][1] =  (A[1][0]*B[0][1] + A[1][1]*B[1][1] )% mod;
  
  return resultantmatrix;
 }
 public static long[][] matrixpowerMod(long[][] A,long power,int mod)
 {
  if(power==0)
  {
   long matrixA[][]={{1,0},{0,1}};
   return matrixA;
  }
  
  else if(power % 2==0)
  {
   long C[][]=matrixpowerMod(A, power/2,mod);
   return matrixmultiplication(C,C,mod);
  }
  else
  {
   return matrixmultiplication(A,matrixpowerMod(A, power-1,mod),mod);
  }
 }
}

Thursday, 20 February 2014

UVA Problem ID 355 (The Bases Are Loaded)

UVA Problem ID 355 (The Bases Are Loaded)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(1000);
		
		while((input=br.readLine())!=null)
		{
			String numbers[]=input.trim().split(" +");
			try {
				BigInteger no=new BigInteger(numbers[2],Integer.parseInt(numbers[0]));
				String ans=no.toString(Integer.parseInt(numbers[1]));
				sb.append(numbers[2]+" base "+numbers[0]+" = "+(ans.toUpperCase())+" base "+numbers[1]);
			} catch (Exception e) {
				sb.append(numbers[2]+" is an illegal base "+numbers[0]+" number");
			}	
			sb.append("\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 343 (What Base Is This?)

UVA Problem ID 343 (What Base Is This?)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main{
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb=new StringBuilder(10000);
		while((input=br.readLine())!=null)
		{
			boolean flag=true;
			
			String numbers[]=input.trim().split(" +");
			for (int i = 2; i < 37; i++) {
				for (int j = 2; j < 37; j++) {
					
					try {//System.out.println(numbers[0].trim()+"  "+Integer.parseInt(numbers[0].trim(),i)+" (base "+i+")"+"____"+numbers[1].trim()+"  "+Integer.parseInt(numbers[1].trim(),j)+" (base "+j+")");
						if(Integer.parseInt(numbers[0].trim(),i)==Integer.parseInt(numbers[1].trim(),j))
						{
							sb.append(numbers[0].trim()+" (base "+i+") = "+numbers[1].trim()+" (base "+j+")");
							sb.append("\n");
							i=38;j=38;flag=false;
						}
					} catch (Exception e) {
						continue;
					}
				}
			}
			if(flag)
			{
				sb.append(numbers[0].trim()+" is not equal to "+numbers[1].trim()+" in any base 2..36");
				sb.append("\n");
			}
		}
		System.out.print(sb);
	}
}

UVA Problem ID 113 (Power of Cryptography)

UVA Problem ID 113 (Power of Cryptography)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        String input;
        while((input=br.readLine())!=null)
        {  	
        	int n=Integer.parseInt(input);
        	double p=Double.parseDouble(br.readLine());
        	sb.append(Math.round(Math.pow(p,(double)1/n)));
        	sb.append("\n");
        }
        System.out.print(sb);
    }
}

UVA Problem ID 10931 (Parity)

UVA Problem ID 10931 (Parity)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        String input;
        while((input=br.readLine())!=null)
        {  	
        	int I=Integer.parseInt(input);
        	if(I==0)
        		break;
        	String s=Integer.toBinaryString(I);
        	int onbits=Integer.bitCount(I);
        	
        	sb.append("The parity of "+s+" is "+onbits+" (mod 2).");
        	sb.append("\n");
        }
        System.out.print(sb);
    }
}

UVA Problem ID 10035 (Primary Arithmetic)

UVA Problem ID 10035 (Primary Arithmetic)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        String input;
        int noofoperation=0;
        while((input=br.readLine())!=null)
        {  noofoperation=0;	
        	String s[]=input.split(" ");
        	
        	if(s[0].equals("0") && s[1].equals("0"))
        		break;
        	int maxlength=s[1].length()>s[0].length()?s[1].length():s[0].length();
        	int carry=0;
        	while(s[0].length()=0; i--)
			{
				int sum=Integer.parseInt(s[0].charAt(i)+"")+Integer.parseInt(s[1].charAt(i)+"")+carry;
				carry=0;
				if(sum>=10)
				{	
					carry=1;
					noofoperation++;
				}
			}
        	if(noofoperation==0)
        		sb.append("No carry operation.\n");
        	else if(noofoperation==1)
        		sb.append("1 carry operation.\n");
        	else
        		sb.append(noofoperation+" carry operations.\n");
        }
        System.out.print(sb);
    }
}

UVA Problem ID 725 (Division)

UVA Problem ID 725 (Division)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        String input;
        int t=0;
        while((input=br.readLine())!=null)
        {  	
        	int N=Integer.parseInt(input);
        	if(N==0)
        		break;
        	if(t!=0)
        	{
        		sb.append("\n");
        	}
        	t=1;
        	boolean flag=false;
        	for (long i =1234; i <98765; i++)
        	{
        		if(isdiffdigits(i+""))
				{
					long a=N*i;
					if(isdiffdigits(a+"") && isdiffdigits(i+"",a+""))
					{
						flag=true;
						if((i+"").length()<5)
							sb.append(a+" / 0"+i+" = "+N+"\n");
						else
							sb.append(a+" / "+i+" = "+N+"\n");
					}
				}
			}
        	if(!flag)
        		sb.append("There are no solutions for "+N+".\n");
        	
        }
        System.out.print(sb);
    }
	public static boolean isdiffdigits(String N)
	{
		if(N.length()<5)
			N=0+N;
		for (int i = 0; i < N.length()-1; i++)
		{
			for (int j = i+1; j < N.length(); j++)
			{
				if(N.charAt(i)==N.charAt(j))
					return false;
			}
		}
		return true;
	}
	public static boolean isdiffdigits(String N1,String N2)
	{
		if(N1.length()<5)
			N1=0+N1;
		if(N2.length()<5)
			N2=0+N2;
		for (int i = 0; i < N1.length(); i++)
		{
			for (int j = 0; j < N2.length(); j++)
			{
				if(N1.charAt(i)==N2.charAt(j))
					return false;
			}
		}
		return true;
	}
}

UVA Problem ID 11804 (Argentina)

UVA Problem ID 11804 (Argentina)
//Note:-BAD ALGORITHM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;


public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        int testcase=Integer.parseInt(br.readLine());
        String playersname[]=new String[10];
        int playersability[][]=new int[10][2];
        for (int i = 0; i < testcase; i++)
		{
        	for (int j = 0; j < 10; j++)
        	{
        		String s[]=br.readLine().split(" ");
        		playersname[j]=s[0];
        		playersability[j][0]=Integer.parseInt(s[1]);
        		playersability[j][1]=Integer.parseInt(s[2]);
        	}
        	int max=0;
        	boolean isattacker[]=new boolean[10];
        	for (int b =0; b < 10-4; b++)
    		{
    			for (int c =b+1;c<10-3; c++)
    			{
    				
    				for (int d =c+1;d<10-2; d++)
    				{
    					
    					for (int e=d+1;e<10-1; e++)
    					{
    						
    						for (int f =e+1; f<10; f++)
    						{
    							int totalattack=playersability[b][0]+playersability[c][0]+playersability[d][0]+playersability[e][0]+playersability[f][0];
    							if(totalattack>max)
    							{
    								for (int j = 0; j < isattacker.length; j++)
									{
										isattacker[j]=false;
									}
    								isattacker[b]=true;
    								isattacker[c]=true;
    								isattacker[d]=true;
    								isattacker[e]=true;
    								isattacker[f]=true;
    					
    								max=totalattack;
    							}
    							else if(totalattack==max)
    							{
    								int totaldefence=0;
    								int olddefence=0;
    								for (int j = 0; j < isattacker.length; j++)
									{
										if(!isattacker[j])
										{
											olddefence+=playersability[j][1];
										}
									}
    								for (int j = 0; j < playersability.length; j++)
									{
										if(j!=b && j!=c && j!=d && j!=e && j!=f)
											totaldefence+=playersability[j][1];
									}
    								if(olddefence0)
											{
												//ans a1
												for (int j1 = 0; j1 < isattacker.length; j1++)
												{
													isattacker[j1]=false;
												}
												isattacker[b]=true;
		        								isattacker[c]=true;
		        								isattacker[d]=true;
		        								isattacker[e]=true;
		        								isattacker[f]=true;
		        								max=totalattack;
		        								break;
											}
											
										}
										
											
    								}
    							}
       						}
    					}
    				}
    			}
    		}
        	String attackers[]=new String[5];
        	String defender[]=new String[5];
        	int t=0,q=0;
            	for (int j = 0; j < isattacker.length; j++)
				{
            		if(isattacker[j])
            		{
            				attackers[t++]=playersname[j];
            		}
            		else
            			defender[q++]=playersname[j];
				}
            	Arrays.sort(attackers);
            	Arrays.sort(defender);
            	sb.append("Case "+(i+1)+":\n");
            	sb.append("("+attackers[0]);
            	for (int j = 1; j < attackers.length; j++)
				{
            		sb.append(", "+attackers[j]);
				}
            	sb.append(")\n");
            	
            	sb.append("("+defender[0]);
            	for (int j = 1; j < defender.length; j++)
				{
            		sb.append(", "+defender[j]);
				}
            	sb.append(")\n");
		}
        System.out.print(sb);
    }
}

UVA Problem ID 10018 (Reverse and Add)

UVA Problem ID 10018 (Reverse and Add)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        String input;
        int testcase=Integer.parseInt(br.readLine());
       
        for (int i = 0; i < testcase; i++)
		{
        	input=br.readLine();
        	int iteations=0;
        	while(!ispalindrome(input))
        	{
        		long sum=Long.parseLong(input)+Long.parseLong(new StringBuilder(input).reverse().toString());
        		input=sum+"";
        		iteations++;
        	}
        	sb.append(iteations+" "+input+"\n");
		}
        System.out.print(sb);
    }
	public static boolean ispalindrome(String s)
	{
		StringBuilder sb1=new StringBuilder(s);
		String s1=new String(sb1.reverse());
		
		if(s.equals(s1))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

UVA Problem ID 441 (Lotto)

UVA Problem ID 441 (Lotto)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder("");
        String input;
        int testcase=0;
        while((input=br.readLine())!=null)
        {
        	String inputarr[]=input.split(" ");
        	int k=Integer.parseInt(inputarr[0]);
        	if(k==0)
        		break;
        	if(testcase!=0)
        	{
			sb.append("\n");
		}
		testcase=1;
        	int S[]=new int[k];
        	for (int i = 0; i < S.length; i++)
			{
				S[i]=Integer.parseInt(inputarr[i+1]);
			}
        	
        	for (int a = 0; k-a > 5; a++)
			{
        		for (int b = a+1; k-b > 4; b++)
        		{
        			for (int c = b+1; k-c >3; c++)
        			{
        				for (int d =c+1; k-d >2; d++)
        				{
        					for (int e=d+1; k-e>1; e++)
        					{
        						for (int f = e+1; k-f >0; f++)
        						{
        							sb.append(S[a]+" "+S[b]+" "+S[c]+" "+S[d]+" "+S[e]+" "+S[f]);
        							sb.append("\n");
        						}
        					}
        				}
        			}
        		}
            	
			}
        }
        System.out.print(sb);
    }
}

UVA Problem ID 12356 (Army Buddies)

UVA Problem ID 12356 (Army Buddies)

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;


public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedOutputStream output = new BufferedOutputStream(System.out);
		StringBuilder sb = new StringBuilder(10000);
		int left[]=new int[100001];
		int right[]=new int[100001];
		int S,B;
		String input;
		while((input=br.readLine())!=null)
		{
			StringTokenizer s=new StringTokenizer(input);
			S=Integer.parseInt(s.nextToken());
			B=Integer.parseInt(s.nextToken());
			if(S==0 && B==0)
				break;
			
			for (int i =0; i = 10000) {

                output.write(sb.toString().getBytes());

                sb = new StringBuilder(25000);

            }

		}
		output.write(sb.toString().getBytes());

        output.flush();

        output.close();
		
	}
}

UVA Problem ID 10107 (What is the Median?)

UVA Problem ID 10107 (What is the Median?)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.TreeSet;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuilder sb = new StringBuilder("");
		TreeSet ts=new TreeSet();
		int ar[]=new int[10000];
		int k=0;
		while((input=br.readLine())!=null)
		{
			input=input.trim();
			int n=Integer.parseInt(input);
			ar[k++]=n;
			Arrays.sort(ar,0,k);
				
			if((k)%2!=0)
			{
				sb.append(ar[k/2]);
			}
			else
			{
				sb.append((ar[k/2-1]+ar[k/2])/2);

			}
			sb.append("\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 10038 (Jolly Jumpers)

UVA Problem ID 10038 (Jolly Jumpers)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuffer sb = new StringBuffer("");
		while((input=br.readLine())!=null)
		{
			String s[]=input.split(" ");
			int n=Integer.parseInt(s[0]);
			if(n>3000)
				break;
			int sequence[]=new int[n];
			boolean flag[]=new boolean[n-1];
			for (int i = 0; i < sequence.length; i++)
			{
				sequence[i]=Integer.parseInt(s[i+1]);
			}
			for (int i = 0; i < sequence.length-1; i++)
			{
				int diff=Math.abs(sequence[i]-sequence[i+1]);
				//System.out.println("diff ="+diff);
				if(diff >=1 && diff<=n-1)
				{
					flag[diff-1]=true;
				}
			}
			boolean isjolly=true;
			for (int i = 0; i < flag.length; i++)
			{
				if(!flag[i])
				{
					isjolly=false;
					break;
				}
			}
			if(isjolly)
				sb.append("Jolly\n");
			else
				sb.append("Not jolly\n");
		}
		System.out.print(sb);
	}
}

UVA Problem ID 10226 (Hardwood Species)

UVA Problem ID 10226 (Hardwood Species)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        String input;
        int testcases=Integer.parseInt(br.readLine());
        br.readLine();
        for (int t = 0; t < testcases; t++)
		{
        	if(t>0)
        		sb.append("\n");
        	TreeMap tm=new TreeMap<>();
        	int count=0;
			while((input=br.readLine())!=null)
			{
				if(input.trim().equals(""))
					break;
	        	count++;
	        	
	        	if(tm.containsKey(input))
	        	{
	        		tm.put(input,tm.get(input)+1);
	        	}
	        	else
	        	{
	        		tm.put(input,1);
	        	}
	        }
			Set> set=tm.entrySet();
			
			Iterator> i=set.iterator();
			
			while(i.hasNext())
			{
				Map.Entry me=(Map.Entry)i.next();
				double fraction=((double)me.getValue()/count)*100;
				DecimalFormat df=new DecimalFormat("0.0000");
				sb.append(me.getKey()+" "+df.format(fraction));
				sb.append("\n");
			}
		}
        System.out.print(sb);
    }
}

UVA Problem ID 459 (Graph Connectivity)

UVA Problem ID 459 (Graph Connectivity)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main
{
	static int pset[];
	 
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuffer sb = new StringBuffer("");
		int testcases = Integer.parseInt(br.readLine());
		br.readLine();
		for (int i = 0; i < testcases; i++)
		{
			if(i>0)
				sb.append("\n");
			int largest=br.readLine().charAt(0)-64;
			initSet(largest);
			while((input=br.readLine())!=null)
			{
				if(input.trim().equals(""))
					break;
				
				union(input.charAt(0)-65,input.charAt(1)-65);
//				UnionFindDisjoint1.print();
				
			}
			
//			Set set=UnionFindDisjoint1.unique();
			sb.append(numberOfSets()+"\n");
			
		}
		System.out.print(sb);
	}
	public static int findSet(int i)
	{
		return (pset[i] == i) ? i : (pset[i] = findSet(pset[i]));
	}
	public static void  union(int i,int j)
	{
		pset[findSet(i)] = findSet(j);
	}
	public static void initSet(int size)
	{
		pset=new int[size];
		for (int i = 0; i < size; i++)
		{
			pset[i]=i;
		}
	}
	public static int numberOfSets()
	{
		int numerofsets=0;
		for (int i = 0; i < pset.length; i++)
		{
			if(pset[i] == i)
				numerofsets++;
		}
		return numerofsets;
	}
}

UVA Problem ID 793 ( Network Connections)

UVA Problem ID 793 ( Network Connections)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
 public static void main(String[] args) throws IOException
 {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuffer sb = new StringBuffer("");
  int testcases = Integer.parseInt(br.readLine());
  br.readLine();

  for (int i = 0; i < testcases; i++)
  {
   if(i>0)
    sb.append("\n");
   int no_of_computers=Integer.parseInt(br.readLine());
   
   UnionFindDisjoint.initSet(no_of_computers);
   int N1=0;
   int N2=0;
   while((input=br.readLine())!=null)
   {
    if(input.trim().equals(""))
     break;
    String s[]=input.split(" ");
    switch (s[0])
    {
     case "c":
     {
      UnionFindDisjoint.union(Integer.parseInt(s[1])-1,Integer.parseInt(s[2])-1);
      break;
     }
     case "q":
     {
      if(UnionFindDisjoint.isSameSet(Integer.parseInt(s[1])-1,Integer.parseInt(s[2])-1))
      {
       N1++;
      }
      else
       N2++;
      break;
     }
    }
   }
   sb.append(N1+","+N2+"\n");
  }
  System.out.print(sb);
 }
}
class UnionFindDisjoint
{
 static int pset[];
 public static void initSet(int size)
 {
  pset=new int[size];
  for (int i = 0; i < size; i++)
  {
   pset[i]=i;
  }
 }
 public static int findSet(int i)
 {
  return (pset[i] == i) ? i : (pset[i] = findSet(pset[i]));
 }
 public static void  union(int i,int j)
 {
  pset[findSet(i)] = findSet(j);
 }
 public static boolean isSameSet(int i,int j)
 {
  return findSet(i) == findSet(j);
 }
}

Saturday, 25 January 2014

UVa Problem ID 11308 (Bankrupt Banker)

UVa Problem ID 11308 (Bankrupt Banker)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;

public class Main
{
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        int testcases=Integer.parseInt(br.readLine());
        if(testcases<1 || testcases>100)
        	System.exit(0);
        for (int t = 0; t < testcases; t++)
		{
        	
        	sb.append(br.readLine().toUpperCase()+"\n");
        	String s[]=br.readLine().split(" ");
        	int m=Integer.parseInt(s[0]);
        	int n=Integer.parseInt(s[1]);
        	int b=Integer.parseInt(s[2]);
        	
        	if(m<1 || m>100 || n<1 || n>100 || b<1 || b>1000000)
        		break;
        	
        	HashMap ingredientcost=new HashMap<>();
        	TreeSet recipes=new TreeSet<>(new Comparator()
			{
				@Override
				public int compare(Recipe r1,Recipe r2)
				{
					if(r1.cost>r2.cost)
						return 1;
					else if(r1.cost==r2.cost)
						return r1.name.compareTo(r2.name);
					else
						return -1;
				}
			});
        	for (int i = 0; i 100)
					break;
				int cost=0;
				for (int j = 0; j < k; j++)
				{
					String s2[]=br.readLine().split(" ");
					cost+=ingredientcost.get(s2[0])*Integer.parseInt(s2[1]);
				}
				//System.out.println("cost ="+cost);
				r1.cost=cost;
				recipes.add(r1);
			}
        	boolean inbudget=false;
        	Iterator i=recipes.iterator();
        	while (i.hasNext())
			{
				Recipe recipe = (Recipe) i.next();
				if(recipe.cost<=b)
				{
					inbudget=true;
					sb.append(recipe.name+"\n");
				}
			}
        	if(!inbudget)
        	{
        		sb.append("Too expensive!\n");
        	}
        	sb.append("\n");
		}
        System.out.print(sb);
    }
}
class Recipe
{
	String name;
	int cost;
	
	public Recipe(String s)
	{
		name=s;
	}
}

UVa Problem ID 11495 (Bubbles and Buckets)

UVa Problem ID 11495 (Bubbles and Buckets)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	static long swapcount=0;
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        while(true)
        {
        	swapcount=0;
        	String s[]=br.readLine().split(" ");
	        int n=Integer.parseInt(s[0]);
	        if(n<2 || n>100000)
	        	break;
	        int a[]=new int[n];
	
	        for (int i = 0; i < n; i++) {
	        	a[i]=Integer.parseInt(s[i+1]);
				if(a[i]<1 || a[i]>n)
					System.exit(0);
				
			}

	        merge_sort(a,0,a.length-1);

	        if(swapcount%2==0)
	        	sb.append("Carlos");
	        else
	        	sb.append("Marcelo");
	        sb.append("\n");
        }
        System.out.print(sb);
    }
	public static void merge_sort(int[] a,int start,int end) {
			if(startmiddle)
			{
				combinedarray[k]=a[j++];
			}
			else if(j>end)
			{
				combinedarray[k]=a[i++];
			}
			else
			{
				if(a[i]>a[j])
				{
					combinedarray[k]=a[j++];
					swapcount+=middle-i+1;
				}
				else
					combinedarray[k]=a[i++];
			}
			
		}
		int p=0;
		for (int j2 = start; j2 <=end; j2++)
		{
			a[j2]=combinedarray[p++];
		}
	}	
	

}

UVa Problem ID 10810 (Ultra Quicksort)

UVa Problem ID 10810 (Ultra Quicksort)
//Note :- use long , int is not enough

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	static long swapcount=0;
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        while(true)
        {
        	swapcount=0;
	        int n=Integer.parseInt(br.readLine());
	        if(n==0 || n>500000)
	        	break;
	        long a[]=new long[n];
	
	        for (int i = 0; i < n; i++) {
	        	a[i]=Long.parseLong(br.readLine());
				if(a[i]<0 || a[i]>999999999)
					break;
				
			}
//	        for (int i = 0; i < a.length; i++) {
//				System.out.print(a[i]+" ");
//			}
//	        System.out.println("");
	        merge_sort(a,0,a.length-1);
//	        for (int i = 0; i < a.length; i++) {
//				System.out.print(a[i]+" ");
//			}
//	        System.out.println("");
	        sb.append(swapcount+"\n");
        }
        System.out.print(sb);
    }
	public static void merge_sort(long[] a,int start,int end) {
			if(startmiddle)
			{
				combinedarray[k]=a[j++];
			}
			else if(j>end)
			{
				combinedarray[k]=a[i++];
			}
			else
			{
				if(a[i]>a[j])
				{
					combinedarray[k]=a[j++];
					swapcount+=middle-i+1;
				}
				else
					combinedarray[k]=a[i++];
			}
			
		}
		int p=0;
		for (int j2 = start; j2 <=end; j2++)
		{
			a[j2]=combinedarray[p++];
		}
	}	
	

}

UVa Problem ID 673 (Parentheses Balance)

UVa Problem ID 673 (Parentheses Balance)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuffer sb = new StringBuffer("");
		int testcases = Integer.parseInt(br.readLine());

		for (int i = 0; i < testcases; i++)
		{
			boolean iscorrect = true;
			input = br.readLine();
			Stack st = new Stack();
			for (int j = 0; j < input.length(); j++)
			{
				if (iscorrect)
				{
					switch (input.charAt(j))
					{
						case '(':
						{
							st.push('(');
							break;
						}
						case '[':
						{
							st.push('[');
							break;
						}
						case ']':
						{
							if(st.isEmpty())
							{
								iscorrect=false;
								break;
							}
							char c = st.pop();
							if (c != '[')
							{
								iscorrect = false;
							}
							break;
						}
						case ')':
						{
							if(st.isEmpty())
							{
								iscorrect=false;
								break;
							}
							char c = st.pop();
							if (c != '(')
							{
								iscorrect = false;
							}
							break;
						}
					}
				}
			}
			if(iscorrect && st.isEmpty())
				sb.append("Yes");
			else
				sb.append("No");
			sb.append("\n");
		}
		System.out.print(sb);
	}

}

UVa Problem ID 458 (The Decoder)

UVa Problem ID 458 (The Decoder)
//Note:-be careful about encoding

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
	public static void main(String[] args) throws IOException 
    {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in,"ISO-8859-1"));        
		OutputStreamWriter cout = new OutputStreamWriter(System.out, "ISO-8859-1");

        StringBuffer sb=new StringBuffer("");
        String input;
        while ((input=br.readLine())!=null) {
        	for (int i = 0; i 

UVa Problem ID 10071 (Back To High School Physics)

UVa Problem ID 10071 (Back To High School Physics)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        String input;
        while ((input=br.readLine())!=null) {
			String s[]=input.split(" ");
			int v=Integer.parseInt(s[0]);
			int t=Integer.parseInt(s[1]);
			if(v<-100 || v>100 || t<0 || t>200)
				break;
			sb.append((2*v*t));
			sb.append("\n");
        }
        System.out.print(sb);
    }
}

UVa Problem ID 11462 (Age Sort)

UVa Problem ID 11462 (Age Sort)
//Note :-another approach use counting sort

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        while(true)
    	{
	    	int n=Integer.parseInt(br.readLine());
	    	if(n<=0 || n>2000000)
	        	break;
	        String s[]=br.readLine().split(" ");
	        int ages[]=new int[n];
	        for (int i = 0; i 

Thursday, 23 January 2014

UVa Problem ID 612 (DNA Sorting)

UVa Problem ID 612 (DNA Sorting)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        StringBuffer sb=new StringBuffer("");
        int M=Integer.parseInt(br.readLine());
        boolean blank = false;
       
        for (int i = 0; i 50 || m<=0 || m>100)
				break;
			
			String in[]=new String[m];
			int value[]=new int[m];
			
			
			for (int j = 0; j input.charAt(j2))
						{
							total+=1;
						}
					}
				}
				
				in[j]=input;
				value[j]=total;
			}
			
			for(int j=1;j0 && value[j2-1]>value[j2])
	            {
	                int temp=value[j2-1];
	                value[j2-1]=value[j2];
	                value[j2]=temp;
	                String s1=in[j2-1];
					in[j2-1]=in[j2];
					in[j2]=s1;
	                j2--;
	            }
	            
	        }
			
			if ( blank ) sb.append("\n");
	        blank = true;
			for (int j = 0; j < m; j++) {
//				if(in[j]==null)
//					in[j]="";
				sb.append(in[j]+"\n");
				
			}
			
		}
        System.out.print(sb);
    }
	
}

UVa Problem ID 299 (Train Swapping)

UVa Problem ID 299 (Train Swapping)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        int testcases=Integer.parseInt(br.readLine());
        for (int i = 0; i 50)
        		System.exit(0);
        	int a[]=new int[L];
        	String s[]=br.readLine().split(" ");
        	for(int j=0;ja[j2])
					{
						int temp=a[j2];
						a[j2]=a[j];
						a[j]=temp;
						swapcount++;
					}
				}
			}
        	sb.append("Optimal train swapping takes "+swapcount+" swaps.\n");
        }
        System.out.print(sb);
    }
}

UVa Problem ID 10055 (Hashmat The Brave Warrior)

UVa Problem ID 10055 (Hashmat The Brave Warrior)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        String input;
        while ((input=br.readLine())!=null) {
			String s[]=input.split(" ");
			long a=Long.parseLong(s[0]);
			long b=Long.parseLong(s[1]);
			if(a>b)
				sb.append((a-b));
			else
				sb.append((b-a));
			sb.append("\n");
		}
        System.out.print(sb);
    }
}

UVa Problem ID 10258 (Contestant scoreboard)

UVa Problem ID 10258 (Contestant scoreboard)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
        String input;
        int testcases=Integer.parseInt(br.readLine());
        br.readLine();
        for (int i = 0; i 0)
        		sb.append("\n");
			
			int no_of_contestants=0;
			Contestant contestants[]=new Contestant[100];
			 while ((input = br.readLine()) != null) {
	                if (input.trim().equals("")) {
	                    break;
	                }
				String s[]=input.split(" ");
				//System.out.println("**********"+input+"*********");
				if(Integer.parseInt(s[0]) < 0 || Integer.parseInt(s[0])>100 ||Integer.parseInt(s[1])<1 ||Integer.parseInt(s[1])>9)
						break;
				boolean found=false;
				Contestant c=null;
				for (int j = 0; j 
{
	int number;
	int problemsolved;
	int totaltime;
	HashMap unsolved=new HashMap();
	HashMap solved=new HashMap();
	public Contestant(int no)
	{
		number=no;
	}
		
	@Override
	public int compareTo(Contestant B) {
		if(this.problemsolved>B.problemsolved)
			return -1;
		else if(this.problemsolvedB.totaltime)
				return +1;
			else
			{
				if(this.number

UVa Problem ID 10194 (Football)

UVa Problem ID 10194 (Football)
/*Note:-
!!! The default system encoding is different from the judge data files. !!!

For the detail, please reference this thread:
http://acm.uva.es/board/viewtopic.php?f=10&t=32047&start=30#p140856
 
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in,"ISO-8859-1"));
        OutputStreamWriter cout = new OutputStreamWriter(System.out, "ISO-8859-1");
        StringBuffer sb=new StringBuffer("");
        int N=Integer.parseInt(br.readLine());
        if(N<=0 || N>1000)
        	System.exit(0);
        for (int k1 = 0; k1 0)
        		sb.append("\n");
        	String tournamentname=br.readLine();
        	if(tournamentname.length()<0 || tournamentname.length()>100)
        		break;
        	sb.append(tournamentname+"\n");
        	int T=Integer.parseInt(br.readLine());
        	if(T<=1 || T>30)
        		break;
        	
        	Team teams[]=new Team[T];
        	for (int i = 0; i 30)
        			System.exit(0);
        		for (int j = 0; j < s.length(); j++) {
					if(s.charAt(j)<32 || s.charAt(j)=='#' || s.charAt(j)=='@')
						System.exit(0);
				}
        		Team t=new Team(s);
        		teams[i]=t;
			}
        	int G=Integer.parseInt(br.readLine());
        	if(G<0 || G>1000)
        		break;
        	for (int i = 0; i =20 || goal2<0 ||goal2 >=20)
					break;
        		for (int j = 0; j < teams.length; j++) {
					if(teams[j].name.equals(s[0]))
					{
						if(goal1>goal2)
							teams[j].win++;
						else if(goal1==goal2)
							teams[j].tie++;
						else
							teams[j].losses++;
						teams[j].goalscored+=goal1;
						teams[j].goalagainst+=goal2;
					}
					if(teams[j].name.equals(s[2]))
					{
						if(goal2>goal1)
							teams[j].win++;
						else if(goal1==goal2)
							teams[j].tie++;
						else
							teams[j].losses++;
						teams[j].goalscored+=goal2;
						teams[j].goalagainst+=goal1;
					}
				}
        		
			}
        	
        	Arrays.sort(teams,new Team());
        	for (int j = 0; j < teams.length; j++) {
				sb.append((j+1)+") "+teams[j].name+" "+(teams[j].win*3+teams[j].tie*1)+"p, "+(teams[j].win+teams[j].tie+teams[j].losses)+"g ("+teams[j].win+"-"+teams[j].tie+"-"+teams[j].losses+"), "+(teams[j].goalscored-teams[j].goalagainst)+"gd ("+teams[j].goalscored+"-"+teams[j].goalagainst+")");
				sb.append("\n");
			}
        }
        cout.write(sb.toString());
        cout.flush();
    }
}
class Team implements Comparator
{
	String name;
	int win;
	int tie;
	int losses;
	int goalscored;
	int goalagainst;
	
	public Team(String s)
	{
		name=s;
	}
	public Team()
	{

	}
	
	@Override
	public int compare(Team A, Team B) {
		// TODO Auto-generated method stub
		if((A.win*3+A.tie*1)>(B.win*3+B.tie*1))
			return -1;
		else if((A.win*3+A.tie*1)<(B.win*3+B.tie*1))
			return +1;
		else
		{
			if(A.win>B.win)
				return -1;
			else if(A.win(B.goalscored-B.goalagainst))
					return -1;
				else if((A.goalscored-A.goalagainst)<(B.goalscored-B.goalagainst))
					return +1;
				else
				{
					if(A.goalscored>B.goalscored)
						return -1;
					else if(A.goalscored(B.win+B.tie+B.losses))
							return +1;
						else
							return A.name.compareToIgnoreCase(B.name);

					}
				}
			}
		}
	}
}

UVa Problem ID 11340 (Newspaper)

UVa Problem ID 11340 (Newspaper)
//Note:-use long to get the total cent int is not enough

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.HashMap;

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());
        if(N<=0 || N>5)
        	System.exit(0);
        for (int k1 = 0; k1 100)
        	System.exit(0);
        HashMap m=new HashMap();
        long cost = 0;
        for (int i = 0; i 150000)
        	System.exit(0);
        for (int i = 0; i 10000)
        		break;
        	for (int j = 0; j 

UVa Problem ID 594 (One Little, Two Little, Three Little Endians)

UVa Problem ID 594 (One Little, Two Little, Three Little Endians)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        StringBuffer sb=new StringBuffer("");
       
        while((input=br.readLine())!=null)
        {
        	int n=Integer.parseInt(input);
        	sb.append(n+" converts to "+Integer.reverseBytes(n)+"\n");
        }
        System.out.print(sb);
    }
}

UVa Problem ID 11727 (Cost Cutting)

UVa Problem ID 11727 (Cost Cutting)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
       
        int t=Integer.parseInt(br.readLine());
        if(t>20)
        	System.exit(0);
        for (int i = 0; i 10000 || b<1000 || b>10000 || c<1000 || c>10000 || a==b || a==c || b==c)
        		break;
        	int middle=a;
        	if((a

UVa Problem ID 482 (Permutation Arrays)

UVa Problem ID 482 (Permutation Arrays)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
 public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb=new StringBuffer("");
       
        int t=Integer.parseInt(br.readLine());
        if(t<0)
         System.exit(0);
        for (int i = 0; i s1.length)
          min=s1.length;
         for (int j = 0; j 0)
          sb.append("\n");
         for (int j = 0; j < a.length; j++) {
          if(a[j]==null)
           a[j]="";
    sb.append(a[j]+"\n");
   }
         
        }
        System.out.print(sb);
    }

}

UVa Problem ID 11223 (O: dah dah dah!)

UVa Problem ID 11223 (O: dah dah dah!)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        StringBuffer sb=new StringBuffer("");
       
        int t=Integer.parseInt(br.readLine());
        if(t<1 || t>10)
        	System.exit(0);
        for (int i = 0; i 2000)
        		break;
        	int start=0;
        	boolean flag=false;
        	
        	sb.append("Message #"+(i+1)+"\n");
        	while(true)
        	{
        		String s;
        		if(input.indexOf(" ",start)!=-1)
        		{
        			s=input.substring(start,input.indexOf(" ",start));
        			start=input.indexOf(" ",start)+1;
           		}
        		else
        		{
        			s=input.substring(start);
            		flag=true;
        		}
        		//System.out.println("____"+s+"______");
        		switch(s)
        		{
        			case ".-":
        			{
        				sb.append("A");
        				break;
        			}
        			case "-...":
        			{
        				sb.append("B");
        				break;
        			}
        			case "-.-.":
        			{
        				sb.append("C");
        				break;
        			}
        			case "-..":
        			{
        				sb.append("D");
        				break;
        			}
        			case ".":
        			{
        				sb.append("E");
        				break;
        			}
        			case "..-.":
        			{
        				sb.append("F");
        				break;
        			}
        			case "--.":
        			{
        				sb.append("G");
        				break;
        			}
        			case "....":
        			{
        				sb.append("H");
        				break;
        			}
        			case "..":
        			{
        				sb.append("I");
        				break;
        			}
        			case ".---":
        			{
        				sb.append("J");
        				break;
        			}
        			case "-.-":
        			{
        				sb.append("K");
        				break;
        			}
        			case ".-..":
        			{
        				sb.append("L");
        				break;
        			}
        			case "--":
        			{
        				sb.append("M");
        				break;
        			}
        			case "-.":
        			{
        				sb.append("N");
        				break;
        			}
        			case "---":
        			{
        				sb.append("O");
        				break;
        			}
        			case ".--.":
        			{
        				sb.append("P");
        				break;
        			}
        			case "--.-":
        			{
        				sb.append("Q");
        				break;
        			}
        			case ".-.":
        			{
        				sb.append("R");
        				break;
        			}
        			case "...":
        			{
        				sb.append("S");
        				break;
        			}
        			case "-":
        			{
        				sb.append("T");
        				break;
        			}
        			case "..-":
        			{
        				sb.append("U");
        				break;
        			}
        			case "...-":
        			{
        				sb.append("V");
        				break;
        			}
        			case ".--":
        			{
        				sb.append("W");
        				break;
        			}
        			case "-..-":
        			{
        				sb.append("X");
        				break;
        			}
        			case "-.--":
        			{
        				sb.append("Y");
        				break;
        			}
        			case "--..":
        			{
        				sb.append("Z");
        				break;
        			}
        			case "-----":
        			{
        				sb.append("0");
        				break;
        			}
        			case ".----":
        			{
        				sb.append("1");
        				break;
        			}
        			case "..---":
        			{
        				sb.append("2");
        				break;
        			}
        			case "...--":
        			{
        				sb.append("3");
        				break;
        			}
        			case "....-":
        			{
        				sb.append("4");
        				break;
        			}
        			case ".....":
        			{
        				sb.append("5");
        				break;
        			}
        			case "-....":
        			{
        				sb.append("6");
        				break;
        			}
        			case "--...":
        			{
        				sb.append("7");
        				break;
        			}
        			case "---..":
        			{
        				sb.append("8");
        				break;
        			}
        			case "----.":
        			{
        				sb.append("9");
        				break;
        			}
        			case ".-.-.-":
        			{
        				sb.append(".");
        				break;
        			}
        			case "--..--":
        			{
        				sb.append(",");
        				break;
        			}
        			case "..--..":
        			{
        				sb.append("?");
        				break;
        			}
        			case ".----.":
        			{
        				sb.append("'");
        				break;
        			}
        			case "-.-.--":
        			{
        				sb.append("!");
        				break;
        			}
        			case "-..-.":
        			{
        				sb.append("/");
        				break;
        			}
        			case "-.--.":
        			{
        				sb.append("(");
        				break;
        			}
        			case "-.--.-":
        			{
        				sb.append(")");
        				break;
        			}
        			case ".-...":
        			{
        				sb.append("&");
        				break;
        			}
        			case "---...":
        			{
        				sb.append(":");
        				break;
        			}
        			case "-.-.-.":
        			{
        				sb.append(";");
        				break;
        			}
        			case "-...-":
        			{
        				sb.append("=");
        				break;
        			}
        			case ".-.-.":
        			{
        				sb.append("+");
        				break;
        			}
        			case "-....-":
        			{
        				sb.append("-");
        				break;
        			}
        			case "..--.-":
        			{
        				sb.append("_");
        				break;
        			}
        			case ".-..-.":
        			{
        				sb.append("\"");
        				break;
        			}
        			case ".--.-.":
        			{
        				sb.append("@");
        				break;
        			}
        			default:
        			{
        				sb.append(" ");
        				break;
        			}
        		}
        		if(flag)
        			break;
        	}
        	if(i+1==t)
        		sb.append("\n");
        	else
        	{
        		sb.append("\n");sb.append("\n");
        	}
        	
        }
        System.out.print(sb);
    }
}

Advertisement