# 程序员进阶之算法练习（三）

### A

```    int maxNum = 1, k = 1;
for (int i = 1; i < n; ++i) {
if (a[i] > a[i - 1]) {
++k;
maxNum = max(maxNum, k);
}
else {
k = 1;
}
}```

### 方法1

```    for (int i = 0; i < n; ++i) {
long long k = 1;
while (k <= a[i]) {
k = k << 1;
}
k -= a[i];

long long left = 0, right = i - 1;
long long l = left, r = right;
while (left < right) { // 寻找 == k的左边界
//            printf("%d %d %d \n", i, left, right);
long long mid = (left + right) / 2;
if (a[mid] > k) {
right = mid - 1;
}
else if (a[mid] < k) {
left = mid + 1;
}
else {
l = mid;
right = mid;
}
}
//        printf("%d %d %d \n ------ \n", i, left, right);
if (a[left] == k) {
l = left;
}
left = 0;
right = i - 1;
while (left < right) { //选择 == k的右边界
//            printf("%d %d %d \n", i, left, right);
long long mid = (left + right) / 2;
if (a[mid] > k) {
right = mid - 1;
}
else if (a[mid] < k) {
left = mid + 1;
}
else {
r = mid;
left = mid + 1;
}
}
//        printf("%d %d %d \n", i, left, right);
if (a[right] == k) {
r = right;
}

if (a[l] == k && a[r] == k && r >= l) {
count += r - l + 1;
//            if (a[l] == a[i]) {
//                --count; // 排除自己
//            }
}```

### 方法2

```#include <map>
map<int,int> M;
long long ans=0;
int main(){
int n,a;
cin>>n;
while(n--){
cin>>a;
for(int i=0;i<=31;i++)  ans+=M[(1LL<<i) - a];
M[a]++;
}
cout<<ans;
}```

### C

```    long long ret = (long long)2 * 10E9;
long long left = 0, right = ret;
while (left < right) {
long long mid = (left + right) / 2;
int j = 0;
for (int i = 0; i < n; ++i) {
while (j < m) {
if (a[i] >= b[j] - mid && a[i] <= b[j] + mid) {
break;
}
++j;
}
}
if (j < m) {
ret = mid;
right = mid;
}
else {
left = mid + 1;
}
}```

### D

```    long long d, k, a, b, t;
cin >> d >> k >> a >> b >> t;

if (d <= k) {
ret = d * a;
}
else {

d -= k;
ret = a * k;

long long left = d % k;
long long c = d / k;

ret += min(k * a + t, k * b) * c;

ret += min(t + left * a, left * b);
}```

172 篇文章86 人订阅

0 条评论

## 相关文章

9540

303100

### scheme实现最基本的自然数下的运算

教一个基本没编过什么程序的朋友scheme，为什么教scheme呢？因为他想学，因为一直听我鼓吹，而他觉得他自己多少有C语言一点基础，而又因为我觉得函数式才...

9130

### 设计模式六大原则——里氏替换原则（LSP）

里氏替换原则（LSP，Liskov Substitution Principle）是关于继承机制的原则，是实现开放封闭原则的具体规范，违反了里氏替...

17410

22170

36090

14450

324100

15500

18730