【发布时间】:2018-12-21 23:59:57
【问题描述】:
我一直在尝试解决这个 HackerEarth 问题,但最后几个测试用例似乎总是超时
我是一年级学生,所以我真的不知道如何很好地优化
我尝试查看 java 解决方案,但它只是将更大的案例放入代码中,有效地消除了优化它的需要
import java.io.*;
import java.util.*;
public class police {
static int t,n,k;
static char[][] test;
static int max = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
t = Integer.parseInt(st.nextToken());
for (int i = 0; i < t; i++) {
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
test = new char[n][n];
int ret = 0;
for (int b = 0; b < n; b++) {
st = new StringTokenizer(br.readLine());
for (int a = 0; a < n; a++) {
test[b][a] = st.nextToken().charAt(0);
}
}
for (int b = 0; b < n; b++) {
ret += solve(test[b]); //calculate each row
}
System.out.println(ret);
}
}
static int solve(char[] a) { //given a row, calculate the maximum number of catches
int ret = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 'P') {
for (int b = i - k; b <= i + k; b++) { //scan area to see if police can catch a thief
if (b >= 0 && b < n && a[b] == 'T') {
a[b] = 'C'; //caught
break;
}
}
a[i] = 'U'; //used
}
}
for (int i = 0; i < n; i++) //count
if (a[i] == 'C')
ret++;
return ret;
}
}
我很确定这与解决方法有关,如果有人可以帮助我,那就太棒了
【问题讨论】:
-
JC Denton - 如此美好的时光!我能给你的唯一提示是单排并计算最大的窃贼。然后继续下一个
-
嗨 - 我认为我的代码可以做到这一点,但它似乎真的很慢。当你有时间看看如何改进它时,你能检查一下我的“解决”方法吗?
标签: java algorithm optimization data-structures