【Codeforces 340D】Bubble Sort Graph

【链接】 我是链接,点我呀:)
【题意】


让你根据冒泡排序的规则
建立一张图
问你这张图的最大独立子集的大小

【题解】


考虑a[i]会和哪些点连边?
必然是在a[i]左边且比它大的数字以及在a[i]右边比它小的数字
(根据冒泡排序的原理)
所以如果选择了a[i]就不能再选择它左边比它大的数字或者在a[i]右边比它小的数字了
(因为肯定有连边)
那么可以选择什么呢?
必然是它左边比它小的数字以及在它右边比它大的数字
(肯定和它们没有连边)

那么想一想
选出来的每个数字都要满足这样的特点
不就是一个上升序列吗?

所以选择一个最长上升序列就ok了!
用二分优化一下就好
mi[i]表示长度为i的最长上升子序列的最后一个元素的最小值

【代码】

import java.io.*;
import java.util.*;

public class Main {
    
    
    static InputReader in;
    static PrintWriter out;
        
    public static void main(String[] args) throws IOException{
        //InputStream ins = new FileInputStream("E:\\rush.txt");
        InputStream ins = System.in;
        in = new InputReader(ins);
        out = new PrintWriter(System.out);
        //code start from here
        new Task().solve(in, out);
        out.close();
    }
    
    static int N = (int)1e5;
    static class Task{

        int n;
        int a[];
        int mi[],R;
        
        public void solve(InputReader in,PrintWriter out) {
            n = in.nextInt();
            a = new int[N+10];
            mi = new int[N+10];
            
            for (int i = 1;i <= n;i++) a[i] = in.nextInt();
            R = 0;
            for (int i = 1;i <= n;i++) {
                int l = 1,r = R,temp = 0;
                while (l<=r) {
                    int mid = (l+r)>>1;
                    if (mi[mid]<=a[i]) {
                        temp = mid;
                        l = mid + 1;
                    }else {
                        r = mid - 1;
                    }
                }
                if (mi[temp+1]==0) {
                    R = temp+1;
                    mi[temp+1] = a[i];
                }else {
                    mi[temp+1] = Math.min(mi[temp+1], a[i]);
                }
            }
            out.println(R);
        }
    }

    

    static class InputReader{
        public BufferedReader br;
        public StringTokenizer tokenizer;
        
        public InputReader(InputStream ins) {
            br = new BufferedReader(new InputStreamReader(ins));
            tokenizer = null;
        }
        
        public String next(){
            while (tokenizer==null || !tokenizer.hasMoreTokens()) {
                try {
                tokenizer = new StringTokenizer(br.readLine());
                }catch(IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        
        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/10396899.html
今日推荐