题目:
蒜头国有 n 座城市,编号分别为 0,1,2,3,…,n−1。编号为 x 和 y的两座城市之间如果要修高速公路,必须花费 x∣y 个金币,其中|
表示二进制按位或。
吝啬的国王想要花最少的价格修建高速公路,使得所有城市可以通过若干条高速公路互相达到。现在请你求出 n=2019时,一共有多少不同的方案,能让所有城市连通并且造价最低。方案数可能很大,你只需输出对 10^9+7取模的结果。
分析:
若 x<y,则 x|y>=y,即两座城市之间修路的话,最少的花费就是城市编号最高的编号数。
每座城市最少花费可以连接的城市数目是 2^(二进制中的1的个数)-1个。比如:编号二进制位 1001,它所能连接的最少花费的城市是1000,0001,0000。
并且可以知道不会重复连接,因为每座城市最少花费连接的城市是其编号二进制的子集(即比起编号小)的城市。
所以总共的方案数就是每座城市可能连接的最少花费的城市数相乘。
代码:
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int mmod=1e9+7;
ll powmod(ll x,ll n,ll m){
ll res=1;
while(n){
if(n&1){
res= (x*res)%m;
}
x = (x*x)%m;
n>>=1;
}
return res;
}
int num1(int n){//求n的二进制中1的个数
int cnt=0;
while(n){
n=n&(n-1);
cnt++;
}
return cnt;
}
int main(){
int n=2019;
ll num[2050];
num[0]=2018;
ll res=1;
for(int i=1;i<2019;i++){
//num[i] = powmod(2,num1(i),mmod)-1;
num[i]=(1<<(num1(i)))-1;
res = (res*num[i])%mmod;
}
printf("%d\n",res);
return 0;
}