ACM-ICPC 2018 徐州赛区网络预赛 A.Hard to prepare(数论+递归)

题意:

有 2^k 个数字[0~2^k-1],将其围成一个圈(可以多次使用),在任何位置的数字其左右两边都不可以是它的补码。问一共有多少种情况。

题解:

我们可以通过对每一个位置进行选择处理,如第一个可以放 2^k 种,则下一个一定是 2^k-1 种,直到最后一个是 2^k-2。但是我们发现还有一种情况就是最后第二个和第一个相同则最后一个的选择只有 2^k-1 种,所以我们假设 n-1 和 1合并不断缩减范围直到长度为 2 或 1,则可以输出答案了。

#include <algorithm>
#include  <iostream>
#include   <cstdlib>
#include   <cstring>
#include    <cstdio>
#include    <string>
#include    <vector>
#include    <bitset>
#include     <stack>
#include     <cmath>
#include     <deque>
#include     <queue>
#include      <list>
#include       <set>
#include       <map>
#define mem(a, b) memset(a, b, sizeof(a))
#define pi acos(-1)
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const int maxn = 1e6+10; 

ll pow2[maxn];

ll qpow(ll a, ll b){
	ll ans = 1;
	while(b){
		if(b&1){
			ans = ans*a%mod;
		}
		a = a*a%mod;
		b >>= 1;
	}
	return ans;
}
ll work(ll n, ll m){
	ll ans = 0;
	if(n == 1){
		return pow2[m];
	}
	else if(n == 2){
		return pow2[m]*(pow2[m]-1)%mod;
	}
	else{
		return (pow2[m]*qpow(pow2[m]-1, n-2)%mod*max(pow2[m]-2, 0ll)%mod+work(n-2,m))%mod;
	}
}
void init(){
	pow2[0] = 1;
	for(int i = 1; i <= maxn; i++){
		pow2[i] = pow2[i-1]*2%mod;
	}
}

int main(){
	init();
	int t;
	scanf("%d", &t);
	while(t--){
		ll n, m;
		scanf("%lld %lld", &n, &m);
		printf("%lld\n", work(n, m));
	}
} 

猜你喜欢

转载自blog.csdn.net/yanhu6955/article/details/82929700