您的位置:首页 > 其它

UVa Problem Solution: 10157 - Expressions

2008-12-03 01:20 555 查看
Let n denotes the length of the expression, d denotes the depth at most, and the count is f(n,d). Obviously, f(n,d) = 0 when n is odd. For other conditions, let us consider where we can find the corresponding parenthesis of the leftmost one. It can be only found at the even places. For place 2, this yields f(2, d-1)*f(n-2,d) ways of correctly built expressions. And for place 4, the number will be f(4, d-1)*f(n-4,d). So we can draw this recurrence from the above observation
f(n,d) = E{i:2->n-2,i+=2:f(i,d-1)*f(n-i,d)}
and and base cases are
f(0,d) = 1 where d >= 0

BTW, I develop a tool to post my code to the UVa online judge automatically. This tool will also replace the local #include's with its real content when uploading the code to the server. So, I haven't to paste the code any more. All the included files could be found on this site.

Code:
/***************************************************************************
* Copyright (C) 2008 by Liu Kaipeng *
* LiuKaipeng at gmail dot com *
***************************************************************************/

/* @JUDGE_ID 00000 10157 C++ "Expressions" */
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <iterator>
#include <string>
#include "big_unsigned.hpp"

using namespace std;

int const nsize = 301;
int const dsize = 151;
big_unsigned numbers[nsize][dsize], results[nsize][dsize];

/*
* Let n denotes the length of the expression, d denotes the depth at most,
* and the count is f(n,d). Obviously, f(n,d) = 0 when n is odd. For other
* conditions, let us consider where we can find the corresponding
* parenthesis of the leftmost one. It can be only found at the even places.
* For place 2, this yields f(2, d-1)*f(n-2,d) ways of correctly built
* expressions. And for place 4, the number will be f(4, d-1)*f(n-4,d).
* So we can draw this recurrence from the above observation
* f(n,d) = E{i:2->n-2,i+=2:f(i,d-1)*f(n-i,d)}
* and and base cases are
* f(0,d) = 1 where d >= 0
*/
void gen_numbers()
{
for (int d = 0; d < dsize; ++d)
numbers[0][d] = 1;
for (int n = 2; n < nsize; n += 2)
for (int d = 1; d < dsize ; ++d)
for (int i = 2; i <= n; i += 2)
numbers
[d] += numbers[i-2][d-1] * numbers[n-i][d];
for (int n = 1; n < nsize; ++n)
for (int d = 1; d < dsize; ++d)
results
[d] = numbers
[d] - numbers
[d-1];
}

int main(int argc, char *argv[])
{
#ifndef ONLINE_JUDGE
freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
#endif

gen_numbers();
for (int n, d; cin >> n >> d; cout << results
[d] << '/n') {}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: