跳到正文

题解

题解:P17088 轻舟已过

a_small_OIer约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年7月14日
更新
2026年7月15日
篇幅
约 3 分钟
获赞
4
题目
P17088

版本

  1. v1当前

P17088 轻舟已过

题意简述

给定偶数 nn,求最大的正整数 xx,满足 x<2nx<2^n,且存在正整数 kk 使得 popcount⁡(x)=k\operatorname{popcount}(x)=k 且 lowbit⁡(x)=2k\operatorname{lowbit}(x)=2^k。

解法

考虑用二进制表示 xx,因为 lowbit⁡(x)=k\operatorname{lowbit}(x)=k,所以 xx (二进制下)的第 kk 位为 11,又因为 popcount⁡(x)=k\operatorname{popcount}(x)=k,所以 xx 中一共有 kk 个 11。为了最大化 xx,取 k=n2k=\frac{n}{2} ,并将剩余的 k−1k-1 个 11 放在最高的 k−1k-1 个位置。此时:

x=(111111⋯⏟k=n2个1000000⋯⏟k=n2个0)2=((2k−1−1)×2n−k+1)+2k=2n−2n−k+1+2k=2n−2n/2\begin{aligned} x&=(\underbrace{111111\cdots}_{k=\frac{n}{2}\text{个}1}\underbrace{000000\cdots}_{k=\frac{n}{2}\text{个}0})_2\\ &=\left((2^{k-1}-1) \times 2^{n-k+1}\right) + 2^k\\ &=2^n - 2^{n-k+1} + 2^k\\ &=2^n - 2^{n/2}\\ \end{aligned}

直接输出即可,时间复杂度 O(1)\mathcal{O}(1),记得开 long long。

代码

咦我赛时怎么写了个 O(n)\mathcal{O}(n) 啊。

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
//十年OI一场空,不开long long见祖宗
int n , N;
LL ans;
int main(){
	//freopen(".in" , "r" , stdin);
	//freopen(".out" , "w" , stdout);
	scanf("%d" , &n);
    N = n / 2;
    for(int i = N ; i < n ; i++)
        ans += 1LL << i;
	printf("%lld\n" , ans);
	return 0;
}

这个是 O(1)O(1) 的:

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
//十年OI一场空,不开long long见祖宗
int n;
int main(){
	//freopen(".in" , "r" , stdin);
	//freopen(".out" , "w" , stdout);
	scanf("%d" , &n);
	int k = n / 2;
	printf("%lld\n" , (1LL << n) - (1LL << k));
	return 0;
}

恭喜我们优化了 2ms。

原文
存档评论2 条抓取于