I am solving the UVA 11340 problem:
Problem Description
News agency pays money for articles according to some rules. Each character has its own value (some characters may have value equals to zero). Author gets his payment as a sum of all character’s values in the article. You have to determine the amount of money that news agency must pay to an author.
Input
The first line contains integer N (0 < N ≤ 5), it is a number of tests. Each test describes an integer K (0 < K ≤ 100), the number of paid characters. On next K lines there are table of paid characters and its values (character values are written in cents). If character can not be found in the table, then its value is equal to zero. Next, there is integer M (0 < M ≤ 150000). Next M lines contain an article itself. Each line can be up to 10000 characters length. Be aware of a large input size, the whole input file is about 7MB.
Output
For each test print how much money publisher must pay for an article in format ‘x.yy$’. Where x is a number of dollars without leading zeros, and yy number of cents with one leading zero if necessary. Examples: ‘3.32$’, ‘13.07$’, ‘71.30$’, ‘0.09$’.
Code
My code is written using Java. I used HashMap
data structure. But I am getting Time Limit Exceeded (TLE)
error from the online judge. I am not seeing any other place to make improvement for better timing. Can anyone help me to find my mistake that is causing TLE? Or is there a better algorithm to solve this problem?
import java.util.HashMap;
import java.util.Scanner;
public class UVA11340 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int k=sc.nextInt();
HashMap<Character, Integer> map=new HashMap<>();
for(int a=0;a<k;a++)
{
String s=sc.next();
int v=sc.nextInt();
map.put(s.charAt(0),v);
}
int l=sc.nextInt();
double cost=0;
sc.nextLine();
for(int b=0;b<l;b++)
{
String str=sc.nextLine();
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
cost=cost+(map.get(c)==null?0:map.get(c));
}
}
cost=cost/100;
System.out.printf("%.2f$\n",cost);
}
sc.close();
}
}