Maximum Value(unique函數,lower_bound()函數,upper_bound()函數的使用)

來源:互聯網
上載者:User

標籤:pre   ORC   遇到   code   使用   space   main   max   代碼   

傳送門

在看大佬的代碼時候遇到了unique函數以及二分尋找的lower_bound和upper_bound函數,所以寫這篇文章來記錄以備複習。

unique函數

在STL中unique函數是一個去重函數, unique的功能是去除相鄰的重複元素(只保留一個),其實它並不真正把重複的元素刪除,是把重複的元素移到後面去了,然後依然儲存到了原數組中,然後 返回去重後最後一個元素的地址,因為unique去除的是相鄰的重複元素,所以一般用之前都會要排一下序。

STL中關於二分尋找的函數有三個lower_bound 、upper_bound  。這兩個函數都運用於有序區間(當然這也是運用二分尋找的前提),下面記錄一下這兩個函數。

ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)演算法返回一個非遞減序列[first, last)中的第一個大於等於值val的位置。

ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)演算法返回一個非遞減序列[first, last)中的第一個大於值val的位置。

思路:枚舉每個數的倍數,然後二分尋找第一個小於該倍數的數字,維護一下最大的答案就可以了。

代碼:

 1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <set> 6 #define INF 0x3f3f3f3f3f 7  8 using namespace std; 9 typedef long long ll;10 const int maxn = 2e5+5;11 int buf[maxn];12 13 14 int main()15 {16     int n;17     scanf("%d",&n);18     memset(buf, -1, sizeof(buf));19     for(int i = 0; i < n; i++)20     {21         scanf("%d",&buf[i]);22     }23     sort(buf, buf + n);24     n = unique(buf, buf + n) - buf;//去重25     int ans = 0,t;26     for(int i = 0; i < n; i++)27     {28         for(int j = buf[i]; j <= buf[n-1]; j += buf[i])29         {30             int pos = lower_bound(buf+i, buf+n, buf[i]+j) - buf - 1;//是從buf[i]的2倍開始搜的31             //printf("pos:%d\n",buf[pos]);32             t = buf[pos] % buf[i];33             ans = max(ans, t);34             if(t == buf[i] - 1)35                 break;36         }37     }38     printf("%d\n",ans);39     return 0;40 }
View Code

 

Maximum Value(unique函數,lower_bound()函數,upper_bound()函數的使用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.