1、钢材切割
代码1思路:
将钢材切割问题优化为:
- 钢材长度n<=10
- 钢材长度n>10
对于n<=10,可以遍历迭代解决;对于n>10,可以分段切割,每次切割i=1,2,。。。10十种情况;
此法有个缺点,n较大时迭代时间长,n=30时,计算时长需要37s。
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int p[11] = { 0,1,5,8,9,10,17,17,20,24,30 };
int max(int a, int b)
{
if (a >= b) return a;
else return b;
}
int fun(int *p, int n)
{
if (n == 0) return 0;
int q = 0;
if (n <= 10)
{
for (int i = 1; i <= n; i++)
q = max(q, p[i] + fun(p,n-i));
}
else {
for(int i=1;i<=10;i++)
q = max(q, p[i] + fun(p, n - i));
}
return q;
}
int main()
{
int n;
while (cin >> n)
{
clock_t start, end;
start = clock();
cout << "最佳收益:" << fun(p,n) << endl;
end = clock();
cout << "time is " << (double)(end - start) / CLOCKS_PER_SEC << endl;
}
}
代码1优化:
可以维护一张最优值表,减少一些重复的迭代(首先计算n=1-10的最佳值,之后就开始维护一张表p,会发现计算速度越来越快)
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int a[11]= { 0,1,5,8,9,10,17,17,20,24,30 };//初值表
int p[1000] = {0};//最优表
int max(int a, int b)
{
if (a >= b) return a;
else return b;
}
//求解n=1-10的最优质
int max_val(int *p,int n)
{
int q = 0;
for (int i = 1; i <= n; i++)
{
q = max(q, p[i] + max_val(p, n - i));
}
if (q > a[n]) p[n] = q;
return q;
}
int fun(int *p, int n)
{
if (n == 0) return 0;
if (p[n] != 0) return p[n];//如果已经求解,那么直接返回值(n<=10已经求解)
int q = 0;
for (int i = 1; i < n; i++)
{
q = max(q, p[i] + fun(p, n - i));
}
if (p[n] < q) p[n] = q;
return q;
}
int main()
{
int n;
//求解n的1-10时候的最小值
for (int i = 1; i <= 10; i++)
max_val(a, i);
for (int i = 1; i <= 10; i++)
p[i] = a[i];//赋值
while (cin >> n)
{
clock_t start, end;
start = clock();
cout << "最佳收益:" << fun(p,n) << endl;
end = clock();
cout << "time is " << (double)(end - start) / CLOCKS_PER_SEC << endl;
}
}
2、军训
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int N;
cin >> N;
while (N--)
{
int num;
cin >> num;
int left = num;
vector<bool> v(num + 1, false);
while (1)
{
if (left > 3)//排除2
{
int count = 0;
for (int i = 1; i <= num; i++)
{
if (v[i] == false)
{
count++;
}
if (count == 2)
{
v[i] = true; count = 0; left--;
}
}
}
if (left <= 3) break;
if (left > 3)//排除3
{
int count = 0;
for (int i = 1; i <= num; i++)
{
if (v[i] == false)
{
count++;
}
if (count == 3)
{
v[i] = true; count = 0; left--;
}
}
}
if (left <= 3) break;
}
for (int i = 1; i <= num; i++)
if (v[i] == false)
cout << i << " ";
cout << endl;
}
//getchar();
//while (1);
return 0;
}
扫描二维码关注公众号,回复:
3591814 查看本文章