|
| 1 | +// |
| 2 | +// algorithm - some algorithms in "Introduction to Algorithms", third edition |
| 3 | +// Copyright (C) 2018 lxylxy123456 |
| 4 | +// |
| 5 | +// This program is free software: you can redistribute it and/or modify |
| 6 | +// it under the terms of the GNU Affero General Public License as |
| 7 | +// published by the Free Software Foundation, either version 3 of the |
| 8 | +// License, or (at your option) any later version. |
| 9 | +// |
| 10 | +// This program is distributed in the hope that it will be useful, |
| 11 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +// GNU Affero General Public License for more details. |
| 14 | +// |
| 15 | +// You should have received a copy of the GNU Affero General Public License |
| 16 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +// |
| 18 | + |
| 19 | +#ifndef MAIN |
| 20 | +#define MAIN |
| 21 | +#define MAIN_Fib |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_Fib |
| 25 | +#define FUNC_Fib |
| 26 | + |
| 27 | +#include <thread> |
| 28 | +#include "utils.h" |
| 29 | + |
| 30 | +size_t Fib(size_t n) { |
| 31 | + if (n <= 1) |
| 32 | + return n; |
| 33 | + else { |
| 34 | + size_t x = Fib(n - 1); |
| 35 | + size_t y = Fib(n - 2); |
| 36 | + return x + y; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +void PFib(size_t n, size_t* ret) { |
| 41 | + if (n <= 1) |
| 42 | + *ret = n; |
| 43 | + else { |
| 44 | + size_t x, y; |
| 45 | + std::thread t1(PFib, n - 1, &x); |
| 46 | + PFib(n - 2, &y); |
| 47 | + t1.join(); |
| 48 | + *ret = x + y; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +size_t PFib(size_t n) { |
| 53 | + size_t ret; |
| 54 | + PFib(n, &ret); |
| 55 | + return ret; |
| 56 | +} |
| 57 | +#endif |
| 58 | + |
| 59 | +#ifdef MAIN_Fib |
| 60 | +int main(int argc, char *argv[]) { |
| 61 | + std::cout << "n\ta\tb\ta == b" << std::endl; |
| 62 | + for (int i = 1; i < std::max(argc, 2); i++) { |
| 63 | + size_t n = get_argv(argc, argv, i, 10); |
| 64 | + size_t a = Fib(n); |
| 65 | + std::cout << n << '\t' << a << '\t' << std::flush; |
| 66 | + size_t b = PFib(n); |
| 67 | + std::cout << b << '\t'; |
| 68 | + std::cout << std::boolalpha << (a == b) << std::endl; |
| 69 | + } |
| 70 | + return 0; |
| 71 | +} |
| 72 | +#endif |
| 73 | + |
0 commit comments