zoukankan      html  css  js  c++  java
  • 递增三元组

    题目

    题目链接

    分析

    直接暴力(O(N^3)),显然超时。

    将三个数组排序,遍历(b)数组,二分找到(a)中小于(b[i])的个数(A),找到(c)中大于(b[i])的个数(C)(ans)+=(A*C)

    时间复杂度,排序(O(N log N)),查找(O(N log N)),总体(O(N log N))

    代码

    自己写二分

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    
    using namespace std;
    
    typedef long long LL;
    
    const int N = 100010;
    
    int n;
    int a[N], b[N], c[N];
    LL ans;
    
    int main()
    {
        scanf("%d", &n);
        for (int i = 0; i < n; i++) scanf("%d", &a[i]);
        for (int i = 0; i < n; i++) scanf("%d", &b[i]);
        for (int i = 0; i < n; i++) scanf("%d", &c[i]);
    
        sort(a, a + n);
        sort(b, b + n);
        sort(c, c + n);
    
        /* 二分:
         *   1. 找边界  
         *   2. 求mid,写check函数
         *   3. 若l = mid则 +1,r = mid不用 +1
         * 
         * 需要注意的是,二分出来的点若在边界则需要特判。
         */
    
        for (int i = 0; i < n; i++)
        {
            int A = 0, C = 0;
            int l = 0, r = n - 1;
            while (l < r)
            {
                int mid = l + r + 1 >> 1;
                if (a[mid] < b[i]) l = mid;
                else r = mid - 1;
            }
            if (a[l] < b[i]) A = l + 1;
            
            l = 0, r = n - 1;
            while (l < r)
            {
                int mid = l + r >> 1;
                if (c[mid] > b[i]) r = mid;
                else l = mid + 1;
            }
            if (c[l] > b[i]) C = n - l;
    
            ans += (LL)A * C;
        }
        
        cout << ans << endl;
        return 0;
    }
    

    lower_bound(), upper_bound();

  • 相关阅读:
    JAVA假期第五天2020年7月10日
    JAVA假期第四天2020年7月9日
    JAVA假期第三天2020年7月8日
    JAVA假期第二天2020年7月7日
    JAVA假期第一天2020年7月6日
    CTF-sql-group by报错注入
    CTF-sql-order by盲注
    CTF-sql-sql约束注入
    CTF-sql-万能密码
    X-Forwarded-for漏洞解析
  • 原文地址:https://www.cnblogs.com/optimjie/p/12346122.html
Copyright © 2011-2022 走看看