这是SEU新生研讨课自学内容。
书本例题
程序
Updated: 2021/03/02
/*
* Project: LPM
* File: Source.cpp
* ------------------
*
* @author: Teddy van Jerry
*
* @version 2021/03/02
* - add validity check
* - modify the loop range
*
* @version 2020/11/02
* - initial version
*
* -------------------
* @acknowledgement
* The bug which was fixed on 2021/03/02
* was found thanks to
* "North London is Red!"
* in CSDN.
* (2021/03/02)
*
*/
#include <iostream>
#include <deque>
using namespace std;
int main()
{
unsigned n = 0;
double max_t = 0;
deque<deque<deque<int>>> L_all;
deque<deque<int>> L;
cout << "Please input L(1):" << endl;
int num;
// input
while (1)
{
deque<int> row;
while (cin >> num)
{
row.push_back(num);
if (getchar() == '\n') break;
}
L.push_back(row);
n = (row.size() > n) ? row.size() : n;
if (L.size() >= n) break;
}
L_all.push_back(L);
// calculate L(2) to L(m)
for (int m = 2; m <= n; m++)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
int max_now = -1;
// The line below used to be line 38.
for (int k = 1; k <= n; k++)
{
// check the validity
// If any of them is -1, there exists no valid path.
if (L_all[0][i - 1][k - 1] == -1 || L_all[m - 2][k - 1][j - 1] == -1) continue;
// The line below used to be line 40.
max_now = max(max_now, L_all[0][i - 1][k - 1] + L_all[m - 2][k - 1][j - 1]);
}
L[i - 1][j - 1] = max_now;
}
}
L_all.push_back(L);
}
// find the maximum
for (int m = 1; m <= n; m++)
for (int i = 0; i != n; i++)
max_t = max(max_t, L_all[m - 1][i][i] / static_cast<double>(m));
//print
cout << "\nT∞ = " << max_t << endl;
return 0;
}
输出示例
分析
充分利用数学公式(详见我的博客 【LaTeX】 案例分析 (4) - C++ Code in LaTeX),用好递推关系式。
ALL RIGHTS RESERVED © 2020 Teddy van Jerry
欢迎转载,转载请注明出处。