using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public class oper
{
int q = 0;
public int getNumber(int num, int[,] r, int max)
{
int n = max;//N代表进来几个包
if (num == 4)
{
if (r[0, 0] < n)
{
q = nmax(getNumber(3, show(r, 0, 3), max - r[0, 0]) + r[0, 1], getNumber(3, show(r, 0, 3), max)); //递归调用比较不拿0包和拿0包的情况。
}
else
{
q=getNumber(3, show(r, 0, 3), max);//0包重量超过背包重量的情况
}
}
if (num == 3)
{
if (r[0, 0] < n)
{
q = nmax(getNumber(2, show(r, 0, 2), max - r[0, 0]) + r[0, 1], getNumber(2, show(r, 0, 2), max));
}
else
{
q=getNumber(2, show(r, 0, 2), max);
}
}
if (num == 2)
{
if (r[0, 0] < n)
{
q = nmax(getNumber(1, show(r, 0, 1), max - r[0, 0]) + r[0, 1], getNumber(1, show(r, 0, 1), max));
}
else
{
q=getNumber(1, show(r, 0, 1), max);
}
}
if (num == 1)
{
if (r[0, 0] < n)
{
q = r[0, 1];
}
else
{
q = 0;
}
}
return q;
}
public int nmax(int a, int b)
{
int m = 0;
if (a > b||a==b)
{
m = a;
}
if (a < b)
{
m = b;
}
return m;
}
public int[,] show(int[,] a, int b, int num)
{
int[,] c = new int[num, 2];
for (int i = 0; i < num; i++)
{
c[i , 0] = a[i+1,0];
c[i , 1] = a[i+1,1];
}
return c;
}
}
static void Main(string[] args)
{
oper m = new oper();
int[,] a = new int[4, 2]{{2,3},{3,5},{5,8},{6,7}};
int b = m.getNumber(4, a, 12);
Console.Write("背包的总重量为{0}",b.ToString());
Console.Read();
}
}
}
0,1背包问题
最新推荐文章于 2024-09-19 11:52:15 发布