DP动态规划--m处理器问题- m processors(FZU - 1442)

DP–m处理器问题- m processors(FZU - 1442)

Description

There are n data packets and m processors in a network communication system. In this problem, you need to distribute the n data packets to the m processors so that the workload of each processor is as balance as possible.
在这里插入图片描述

INPUT:
There are several test cases. Each case contains two lines. There are two integers n and m in the first line. n is the length of the sequence, and m is the number of subsequence you have to divide into. The following line contains n integers representing the sequence. (1<=m,n<=100)

OUTPUT:
Output one real number with two decimal digits in the fraction that represents the expected result for each case.

Sample Input
6 3
2 2 12 3 6 11
Sample Output
12.32

题目解析

1.题目意思:
有n个连续数据包(a1,a2,a3,…,an,ai表示第i个数据包的大小),依次分给m个处理器,每个处理器便相应得到一个规定负载量 f(i,j)(如若a1,a2,a3给第一个处理器,那么第一个处理器的负载量就是 sqrt(a1^2 + a2^2+ a3^2) , 即f(1,3) ),那总会存在一个或多个处理器使其负载量在所有处理器中是最大的,我们设其为Max,我们就要去求在所有分配情况中,Max最小的值为多少,即最优负载量。

2.题目思路:
这里介绍一个类似的题目:DP–乡村邮局问题-Post Office(POJ-1160)
这俩道题目的dp递推很像,可以参照着看,能够更好地理解。

  • 我们这里定义一个二维数组dp[][],其中dp[i][j]表示前 i 个数据包分给 j 个处理器的最优负载量。

  • 对于一个子结构dp[i][j],即 i包分给j个处理器的最优负载量,我们可以这么求:

  • 我们先定义一个中间值k,在确定dp[k][j-1]的情况下

  • 我们可以得到i包分给j个处理器的最优负载量为:前k包给j-1个处理器,k+1到i包给1个处理器的最优负载量,即:

dp[i][j] = max(dp[k][j - 1], f(k + 1,i)) ----其中(j-1<= k <i)

参考代码:
注意我的做法是先不管负载量的开方,先利用平方号内的值dp最后再开方。

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<cstdio>
typedef long long ll;
using namespace std;
ll load[110];
ll bload[110][110];//存放从i到j的负载量的值(即题目中的f(i,j)未开平方前的值 )
ll dp[110][110];//前i包分给j个处理器
int main()
{
	int n, m;
	while (cin >> n >> m) {
		memset(bload, 0, sizeof(bload));
		memset(dp, 0, sizeof(dp));

		for (int i = 1; i <= n; i++) {
			cin >> load[i];
			bload[1][i] = bload[1][i - 1] + load[i] * load[i];//这里也是动态规划的思想
			dp[i][1] = bload[1][i];//这里顺便初始化只有一个处理器的值,这很重要,算是边界值了
			for (int j = 2; j <= i; j++) {
				bload[j][i] = bload[1][i] - bload[1][j - 1];//其实可以用前缀和做,但这样更加清晰点应该。
			}
		}
		for (int j = 2; j <= m && j <= n; j++) {//j为处理器数
			for (int i = j; i <= n; i++) {//i为包数
				dp[i][j] = 0x3f3f3f3f;
				for (int k = j - 1; k < i; k++) {//前k包给j-1个处理器,k+1到i包给1以处理器
					dp[i][j] = min(dp[i][j], max(dp[k][j - 1], bload[k + 1][i]));//最大负载的最小值
				}
			}
		}
		
		if (m > n)
			m = n;
		cout << fixed << setprecision(2);
		double ans = sqrt((double)dp[n][m]);//算出来后再开平方
		ans = floor(ans * 100.0) / 100.0;//题目中要求不四舍五入,这样可以达到这个效果
		cout << ans << endl;
	}

	return 0;
}
  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值