110,534
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace C2CsharpCon
{
class Program
{
static void Main(string[] args)
{
int n, i, box_count, box_volume;
HNODE box_h = new HNODE(), box_t = new HNODE(), box_u = new HNODE(), j = new HNODE();
ELE p = new ELE(), q = new ELE();
Console.WriteLine("输入箱子容积");
box_volume = int.Parse(Console.ReadLine());
Console.WriteLine("输入物品种数");
n = int.Parse(Console.ReadLine());
int[] a = new int[n];
Console.WriteLine("请按体积从大到小顺序输入各物品的体积:");
for (i = 0; i < n; i++) a[i] = int.Parse(Console.ReadLine());
//box_h=box_t= null;
box_count = 0;
for (i = 0; i < n; i++)
{
p.vno = i;
for (j= box_h; j != null; j = j.next)
{
if (j.remainder >= a[i]) break;
if (j == null)
{
j.remainder = box_volume - a[i];
j.head = null;
if (box_h == null) box_h = box_t = j;
else box_t = box_t.next = j;
j.next = null;
box_count++;
}
else
{
j.remainder -= a[i];
}
}
for (q = j.head; q != null && q.link != null; q = q.link) ;
if (q == null)
{
p.link = j.head;
j.head = p;
}
else
{
p.link = null;
q.link = p;
}
}
Console.WriteLine("共使用了箱子"+ box_count);
Console.WriteLine("各箱子装物品情况如下:");
for (j = box_h, i = 1; j != null; j = j.next, i++)
{
Console.WriteLine("第只箱子;"+i);
Console.WriteLine("还剩余容积,所装物品有;" +j.remainder);
for (p = j.head; p != null; p = p.link)
Console.WriteLine("%4d"+p.vno + 1);
Console.ReadLine();
}
}
}
class HNODE
{
public int remainder;
public ELE head;
public HNODE next;
}
class ELE
{
public int vno;
public ELE link;
}
}
for (j= box_h; j != null; j = j.next)
4楼正解!
建议楼主还是看看那个算法的思想,不要随便把C写成C#,或者先了解下这两张语言的不同之处。
PS:我也不懂贪婪算法