1. 程式人生 > >Maximum Value(unique函數,lower_bound()函數,upper_bound()函數的使用)

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

using war ble sed mem stream fine pos lose

傳送門

在看大佬的代碼時候遇到了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()函數的使用)