首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何优化初学者HackerEarth代码

如何优化初学者HackerEarth代码
EN

Stack Overflow用户
提问于 2018-12-22 07:59:58
回答 1查看 456关注 0票数 3

我一直在尝试解决这个HackerEarth问题,但最后几个测试用例似乎总是超时

问题陈述:https://www.hackerearth.com/practice/algorithms/searching/linear-search/practice-problems/algorithm/joker-and-thieves-53e59f4a/

我是一年级学生,所以我真的不知道如何更好地优化它

我尝试查看java解决方案,但它只是将较大的情况放入代码中,有效地消除了对其进行优化的需要。

代码语言:javascript
复制
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;
    }
}

我很确定这与solve方法有关,如果有人能帮助我,那就太棒了

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-22 12:13:07

您是对的,您在solve方法中使用的方法是导致超时的原因。

首先,您需要对algorithm complexityBig O notation有一个概念

问题的约束是:

1 <= N <= 1000

1 <= K <= N * N

这表明您的解决方案的复杂性最高应该是O(N * N)。换句话说,至多嵌套两个for循环,每个循环的复杂度为O(N)。

在您的解决方案中,您将执行以下操作:

代码语言:javascript
复制
for (int b = 0; b < n; b++) {
    ret += solve(test[b]); //calculate each row
}

好的,这个循环是必不可少的,因为你必须遍历网格中的所有行。复杂性:O(N)

然后在你的solve方法中:

代码语言:javascript
复制
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循环才是问题的真正原因,对于较高的K值,外部循环的复杂度是O(N),而内部循环的复杂度也可能是O(N)。因此,这三个for循环的总复杂度可能会达到O(N * N * N),这肯定会超时。

这是我对这个问题的解决方案,我只修改了solve方法:

代码语言:javascript
复制
static int solve(char[] a) { //given a row, calculate the maximum number of catches
        int ret = 0;
        ArrayDeque<Integer> policeMenQueue = new ArrayDeque<>(); // queue for holding positions of policemen
        ArrayDeque<Integer> thievesQueue = new ArrayDeque<>(); // queue for positions of thieves
        for (int i = 0; i < n; i++) {
            if(!policeMenQueue.isEmpty()) { // check if the leftmost policeman can catch a thief at current position (i)
                Integer mostLeftPoliceMan = policeMenQueue.getFirst();
                if(i - mostLeftPoliceMan > k) { // if he cannot then we must remove him as he will no longer be able to catch any thieves
                    policeMenQueue.removeFirst();
                }
            }
            if(!thievesQueue.isEmpty()) { // check if the leftmost thief can be caught be a policeman at current position (i)
                Integer mostLeftThief = thievesQueue.getFirst();
                if(i - mostLeftThief > k) { // if not then we must remove him as he will no longer be caught by any policemen
                    thievesQueue.removeFirst();
                }
            }
            if(a[i] == 'P') {
                if(!thievesQueue.isEmpty()) { // the leftmost thief can be caught by current policeman
                    ret++;
                    thievesQueue.removeFirst(); // ok this thief is caught, remove him
                } else {
                    policeMenQueue.addLast(i); // just add the policeman to keep his position in the queue
                }
            }
            if(a[i] == 'T') {
                if(!policeMenQueue.isEmpty()) { // the current thief can be caught by the leftmost policeman
                    ret++;
                    policeMenQueue.removeFirst(); // ok this policeman has already caught a thief (used), remove him
                } else {
                    thievesQueue.addLast(i); // just add the thief to keep his position in the queue
                }
            }
        }
        return ret;
    }

我的想法是:从左到右循环每一行,正如问题所述:每个警察只能抓到一个小偷,我们想要最大限度地增加被抓小偷的数量,所以每个小偷都被最左边的警察抓住是对我们有利的(因为我们从左到右)。

例如,考虑以下行:

P P T T

想象一下K = 2

我们希望3位置的小偷被1位置的警察抓住,因为这个警察不能抓住4位置的小偷,当然在这种情况下2位置的警察可以抓住两个小偷,但请记住,我们必须最大限度地增加被抓小偷的数量,每个警察只能抓住一个小偷,所以我们希望每个小偷都被能够抓住他的最左边的警察抓住。

我的解决方案依赖于queue数据结构(Java中的ArrayDeque),如果你不知道它是如何工作的,或者我为什么要使用它,可以看看这里:https://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53892027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档