找到递推公式,题目就引刃而解了。数学公式博文没办法写,就写在了word上,切过来了:
用 f 或者 g 都能求出,我两个方法都试了,结果用 g 要比 f 快了近一倍,原本以为 f 会快些,可能是因为往上走红气球天多的缘故。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#include <cassert>
#include <cmath>
#include <functional>
using namespace std;
long long c(int k)
{
return k == 0 ? 1 : c(k - 1) * 3;
}
long long f(int k, int i)
{
if (i == 0) {
return 0;
}
if (k == 0) {
return 1;
}
int k2 = 1 << (k - 1); // 2的k-1次方
if (i >= k2) {
return f(k - 1, i - k2) + c(k - 1) * 2;
}
else {
return f(k - 1, i) * 2;
}
}
long long g(int k, int i)
{
if (i == 0) {
return 0;
}
if (k == 0) {
return 1;
}
int k2 = 1 << (k - 1); // 2的k-1次方
if (i >= k2) {
return 2 * g(k - 1, i - k2) + c(k - 1);
}
else {
return g(k - 1, i);
}
}
int main()
{
ios::sync_with_stdio(false);
int T;
cin >> T;
int kase = 0;
while (T--) {
int k, a, b;
cin >> k >> a >> b;
cout << "Case " << ++kase << ": ";
//cout << f(k, b) - f(k, a - 1) << endl;
cout << g(k, (1 << k) - a + 1) - g(k, (1 << k) - b) << endl;
}
return 0;
}
本文源地址:http://blog.csdn.net/zyq522376829/article/details/46591661