跳到正文

题解

题解:P13617 [ICPC 2024 APC] Bit Counting Sequence

2022tysc0776约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年10月10日
收录
2026年6月4日
更新
2026年11月2日
篇幅
约 2 分钟
获赞
2
题目
P13617

版本

  1. v1当前

小清新做法。

发现如果有 0,那肯定答案是 0。

然后发现如果有 1,就说明这个数一定是 2x2^x,而这种数只有 O(log⁡V)O(\log V) 个,枚举然后判断合不合法即可。

那如果没有 1 呢?发现说明着整个序列的最高位没有变过,直接把所有数减一,最后算答案是加回来即可。

计算一个数中有几个 1 可以通过__builtin_popcount()O(1)O(1) 计算。

时间复杂度 O(nlog⁡V)O(n \log V)。

想法很简单,同时也很好写。

C++
#include <bits/stdc++.h>
using namespace std;
const int N=500005;
#define int long long
const int inf=(1ll<<62)-1;
int T,n,a[N];

signed main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	cin>>T;
	while(T--){
		int minn=61,mid;bool ok=0;
		cin>>n;
		for(int i=1;i<=n;i++) cin>>a[i];
		for(int i=n;i>=1;i--) if(minn>a[i]) minn=a[i],mid=i;
		if(minn==0){
			for(int i=1;i<=n;i++){
				int tx=i-1;
				if(__builtin_popcountll(tx)!=a[i]){
					cout<<"-1\n";	
					ok=1;
					break;
				}
			}
			if(!ok) cout<<"0\n";
			continue;
		}
		int c=minn-1;
		for(int w=1;w<=inf;w<<=1){
			if(w-mid+1<=0) continue;
			int tx=w-mid+1;ok=0;
			for(int i=1;i<=n;i++){
				if(__builtin_popcountll(tx)!=a[i]-c){
					ok=1;
					break;
				}
				tx++;
			}
			if(!ok){
				int ans=w-mid+1;
				while(c){
					w<<=1;
					ans|=w;
					c--;
				}
				cout<<ans<<'\n';
				break;
			}
		}
		if(ok) cout<<"-1\n";
	}
	return 0;
}
原文
存档评论1 条抓取于