Key Set
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1803 Accepted Submission(s): 949
Problem Description
soda has a set
S
with
n
integers
{1,2,…,n}
. A set is called key set if the sum of integers in the set is an even number. He wants to know how many nonempty subsets of
S
are key set.
Input
There are multiple test cases. The first line of input contains an integer
T
(1≤T≤105)
, indicating the number of test cases. For each test case:
The first line contains an integer n (1≤n≤109) , the number of integers in the set.
The first line contains an integer n (1≤n≤109) , the number of integers in the set.
Output
For each test case, output the number of key sets modulo 1000000007.
Sample Input
4 1 2 3 4
Sample Output
0 1 3 7
题意:给你一个具有n个元素的集合S{1,2,…,n},问集合S的非空子集中元素和为偶数的非空子集有多少个。
公式:2^(n-1)-1直接用吧!!!
题中数据大,因此结合快速幂求解:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define mod 1000000007
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
n--;
long long int base=2;
long long int ans=1;
while(n) //求 2^(n-1)
{
if(n&1)
{
ans=(ans*base)%mod;
}
base=(base*base)%mod;
n=n/2;
}
printf("%lld\n",ans-1); //最后减1
}
}
最后加两个模板:
<pre name="code" class="cpp">//快速幂
#include<cstdio>
int quickpow(int n,int m) //做题时一般用__int64(数据太大)
{
int ans=1,base=n;
while(m)
{
if(m&1)
{
ans=(base*ans);
}
base=(base*base);
m>>=1; //m=m/2
}
return ans;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
printf("%d\n",quickpow(n,m));
}
return 0;
} //模板
//快速幂求模,求n^m对常数mod取模
#include<cstdio>
int quickpow(int n,int m,int mod)
{
int ans=1,base=n;
while(m)
{
if(m&1)
{
ans=(base*ans)%mod;
}
base=(base*base)%mod;
m>>=1;
printf("ans=%d base=%d m=%d\n",ans,base,m);
}
return ans;
}
int main()
{
int n,m,mod;
while(~scanf("%d%d%d",&n,&m,&mod))
{
printf("%d\n",mod);
printf("%d\n",quickpow(n,m,mod));
}
return 0;
} //模板