【C++ 程序】 最长路径矩阵(LPM)算法求迭代边界

这是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
欢迎转载,转载请注明出处。


See also

Teddy van Jerry 的导航页

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值