uva12627 - Erratic Expansion 入门经典II 第八章 例题8-12

来源:互联网 发布:淘宝网企业开店费用 编辑:程序博客网 时间:2024/06/01 16:13

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4352


说明:书中有一个地方打印错了,思考了很久,一看代码,果然打印错了。g(k,i)=2g(k-1,i-2的k-1次幂)+c(k)  其中的

c(k) 改为c(k-1);


题中的图: 挺明了的



#include<stdio.h>#include<iostream>using namespace std;long long c(int i){    return i == 0 ? 1 : 3*c(i-1);}long long f(int k,int i){    if(i == 0) return 0;    if(k == 0) return 1;    long long k2 = 1 << (k-1);    if(i >= k2) return f(k-1,i-k2) + 2*c(k-1);    else     return 2*f(k-1,i);}int main(){    int T,kase=1;    cin >>T;    while(T--){        int k,A,B;        cin >> k >> A >> B;        printf("Case %d: %lld\n",kase++,f(k,B)-f(k,A-1));    }    return 0;}



汝佳提供的代码:
// UVa12627 Erratic Expansion// Rujia Liu#include<iostream>using namespace std;// how many red balloons after k hourslong long c(int i) {  return i == 0 ? 1 : c(i-1)*3;}// how many red balloons in the first i rows, after k hourslong long f(int k, int i) {  if(i == 0) return 0;  if(k == 0) return 1;  int k2 = 1 << (k-1);  if(i >= k2) return f(k-1, i-k2) + c(k-1)*2;  else return f(k-1, i) * 2;}// how many red balloons in the last i rows, after k hourslong long g(int k, int i) {  if(i == 0) return 0;  if(k == 0) return 1;  int k2 = 1 << (k-1);  if(i >= k2) return g(k-1, i-k2) + c(k-1);  else return g(k-1,i);}int main() {  int T, k, a, b;  cin >> T;  for(int kase = 1; kase <= T; kase++) {    cin >> k >> a >> b;    cout << "Case " << kase << ": " << f(k, b) - f(k, a-1) << "\n";  }  return 0;}


0 0
原创粉丝点击