ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준/JAVA] 26481 수열과 쿼리 42 - 시간 초과
    ETC/Algorithm 2023. 5. 25. 02:25

    주의


    미해결 문제이므로 참고만 할 것

    제출 코드


    import java.io.*;
    import java.util.*;
    
    class Main {
    
        static int N,Q;
        static int l,r;
        static int[] arr;
        static int[] lis;
        static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine()," ");
    
            N = Integer.parseInt(st.nextToken());
            Q = Integer.parseInt(st.nextToken());
    
            arr = new int[N];
    
            st = new StringTokenizer(br.readLine(), " ");
            for (int i = 0; i < N; i++) {
                arr[i] = Integer.parseInt(st.nextToken());
            }
    
            for (int i = 0; i < Q; i++) {
                st = new StringTokenizer(br.readLine(), " ");
                l = Integer.parseInt(st.nextToken())-1;
                r = Integer.parseInt(st.nextToken())-1;
                int longest = longest();
                bw.write(String.valueOf(longest));
                bw.write("\n");
            }
            bw.flush();
        }
    
        public static int longest() throws IOException {
            lis = new int[r-l+1];
            int j = 0;
            if ((r - l + 1) == N) {
                lis[0] = arr[0];
            } else {
                lis[0] = arr[l];
            }
            for(int i =l ; i < r+1; i++) {
                if (lis[j] < arr[i]) {
                    lis[j + 1] = arr[i];
                    j += 1;
                }
                else {
                    int idx = binarySearch(0, j, arr[i]);
                    lis[idx] = arr[i];
                }
            }
    
            return j + 1;
    
        }
        public static int binarySearch(int left, int right, int target) {
    
            int mid;
    
            while (left < right) {
                mid = (left + right) / 2;
    
                if (lis[mid] < target) {
                    left = mid + 1;
                }
                else {
                    right = mid;
                }
            }
            return right;
        }
    }

    댓글

Designed by black7375.