新人求教C#代码

镜-花水月 2013-04-03 09:51:03
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;
}

}


贪婪算法的装箱求解,可是编译出错,求大神帮忙
...全文
145 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
_小黑_ 2013-04-03
  • 打赏
  • 举报
回复
你 自己 动动脑筋 ,这就跟脑筋急转弯似的
镜-花水月 2013-04-03
  • 打赏
  • 举报
回复
引用 7 楼 KumaPower 的回复:
看了看楼主之前贴的C代码和这里的C#代码,发现连抄都抄错了。。。。。。
求帮忙啊
gxingmin 2013-04-03
  • 打赏
  • 举报
回复
循环前用个临时变量记住j.head var temp=j.head; for (j= box_h; j != null; j = j.next) {... } j=temp; for(...)
镜-花水月 2013-04-03
  • 打赏
  • 举报
回复
大神们求帮忙啊,小弟改了半天才到这样了,实在不会,这还是刚开始看的
Bonjour-你好 2013-04-03
  • 打赏
  • 举报
回复
看了看楼主之前贴的C代码和这里的C#代码,发现连抄都抄错了。。。。。。
Bonjour-你好 2013-04-03
  • 打赏
  • 举报
回复
for (j= box_h; j != null; j = j.next)
4楼正解! 建议楼主还是看看那个算法的思想,不要随便把C写成C#,或者先了解下这两张语言的不同之处。 PS:我也不懂贪婪算法
镜-花水月 2013-04-03
  • 打赏
  • 举报
回复
引用 4 楼 gxingmin 的回复:
你上面的循环 for (j= box_h; j != null; j = j.next) 决定了j肯定是null,所以循环完毕后把j还指向头地址
怎样修改呢?我确实不太会,大神帮帮我
gxingmin 2013-04-03
  • 打赏
  • 举报
回复
你上面的循环 for (j= box_h; j != null; j = j.next) 决定了j肯定是null,所以循环完毕后把j还指向头地址
镜-花水月 2013-04-03
  • 打赏
  • 举报
回复
引用 2 楼 gxingmin 的回复:
测试了你的例子,能编译通过,但是输入数量和体积后会报错,j为null
大神能帮帮忙吗?我还是小白一只
gxingmin 2013-04-03
  • 打赏
  • 举报
回复
测试了你的例子,能编译通过,但是输入数量和体积后会报错,j为null
镜-花水月 2013-04-03
  • 打赏
  • 举报
回复
提示这个错误,大神们帮帮忙

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧