Codeforces Round #447 (Div. 2) B. Ralph And His Magic Field【数论/组合数学】
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.
Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 109 + 7.
Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.
The only line contains three integers n, m and k (1 ≤ n, m ≤ 1018, k is either 1 or -1).
Print a single number denoting the answer modulo 1000000007.
1 1 -1
1
1 3 1
1
3 3 -1
16
In the first example the only way is to put -1 into the only block.
In the second example the only way is to put 1 into every block.
【题意】:有n行m列。拉尔夫可以在每个块中放置一个整数。然而,魔术领域并不总是正常工作。只有在每行和每列中的整数乘积等于k时才有效,其中k是1或-1。现在拉尔夫想让你弄清楚在每个区块中放置数字的方法数量,以使魔法区域正常工作。(那么只能放1 or -1)两种方式被认为是不同的,当且仅当至少存在一个块,其中第一种方式和第二种方式中的数字是不同的。你被要求输出答案%1e9+7。
【分析】:当(n%2) != (m%2)并且k == -1是时输出0, 因为k==-1乘积次数为偶数时得到1,奇数时为-1.
else,试想一行的情况,不管前m-1怎么选择,最后一个都能通过选择(-1 or 1)得到k,同理列的情况也一样,所以最后(n-1)*(m-1)的方格都可以随意选择,然后通过剩下的一行和一列选择就可以得到k。因为只能选择(-1 or 1),答案是 2^((n-1)*(m-1))。
//我们可以将1或-1 放在它里面,总共有pow(2,[(n-1)*(m-1)])方式。 那么很明显,剩下的数字是唯一确定的,因为每行和每列的乘积已经是已知的。
因为n和m都可以到1e18,不能直接2^((n-1)*(m-1))进行快速幂操作。可以进行两次快速幂 或者 指数%(MOD-1)
【代码】:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <bits/stdc++.h> using namespace std; typedef long long LL; const LL mod = 1e9+7; inline LL pows(LL x,LL n)//注意函数名不能为pow(不然一直wa7)因为pow为库函数名而且不是LL的 { LL res=1; while(n) { if(n&1)// res = res * x % mod; n>>=1; x = x * x % mod; } return res; } int main() { LL n,m,k; while(~scanf("%lld%lld%lld",&n,&m,&k)) { if(n%2!=m%2 && k==-1) { printf("0\n"); return 0; } else printf("%lld\n",pows(pows(2, n-1),m-1)); } return 0; }