【发布时间】:2014-01-31 16:44:17
【问题描述】:
我在 c 中有一个问题,我想使用下面编写的代码来实现这种事情。输入输出应该是这样的:
Input Freq Output Freq
1 0,1,4,2,5,3 add two first (0+1) 0,1,4,2,5,3,1
2 4,2,5,3,1 add min and last (2+1) 0,1,4,2,5,3,1,3
3 4,5,3,3 add min and last (3+3) 0,1,4,2,5,3,1,3,6
4 4,5,6 **here we add(4+5)**(minimum two)0,1,4,2,5,3,1,3,6,9
5 9,6 minimum two 0,1,4,2,5,3,1,3,6,9,15
6 15
但条件是必须不能交换元素,不能排序,**但是我们可以处理元素的索引进行比较,如果我们找到了一次我们添加它们并放在数组最后的任何索引处的正确元素。
我正在尝试一些基本的想法它在第一个 if 条件下工作正常,但是在 我想知道的其他两个 if 条件中写什么。请在那里帮助我。 假设 data[i].freq={0,1,2,3,4,5} 和 data[i].next 指向下一个元素,如上面示例中的第一步,0 指向 1,现在这个 1 指向到这两个获得的元素(所以这个 1 至少指向 1 并且最后这个 1 索引将指向“1”的下一个(我们另外使用)所以那个“1”的下一个是 4 ,所以最后一个元素“1”指向 4 并且我们保持索引指向的方式相同)。请不要犹豫,问我是否还没有理解我的意思。 我猜代码应该非常接近这个:
data[data_size].freq=data[0].freq+data[1].freq; // here i add the first 2 elements "0" and "1" in the example i given below.
data[data_size].flag=0; //I am using flag variable to show which elements are added or which are not added even once. If flag ="1" then that element is added if it "0" then not added even once.
data[0].flag=1;
data[1].flag=1; //these two have been added.
int count=5;
do
{
for(i=0;data[i].next!=-1;i=data[i].next)
{
if(data[data[i].next].freq>data[data_size].freq && data[data[i].next].flag==0)//Here i am setting flag=0 for those elements who not have been added yet. Because we don't have to take in account for addition those elements who are already added once.(step1 and step2 are coming in this loop)
{
data[data_size+1].freq= data[data_size].freq+ data[data[i].next].freq;
data[data_size].flag=1;//those elements which we are adding we set their flag to 1
data[data[i].next].flag=1;
data[data_size+1].flag=0;//this is the element onbtained on result will be sent to last index.With 0 flag because it is not added yet.
data[data_size].next=data[i].next;
data[i].next=data_size;
data_size++;
}
if(data[data[i].next].freq<data[data_size].freq && data[data[i].next].flag==0)
{
//some code for step4 where 6>5 (in this case we added 5+4)
data_size++;
}
if(data[data[i].next].freq==data[data_size].freq && data[data[i].next].flag==0)
{
//Some code for step3 when element are equal
data_size++;
}
}
count--;
} while(count>0)
会有不同的条件,例如(最后一个元素= 找到右侧的元素,例如步骤 2 中的 3+3=6),找到的元素比 5+4=9 等最后一个元素更小(参见步骤 4)
知道在其他两个 if 条件下应该做什么吗?我的数组输入必须是{0,1,4,2,5,3}(我的意思是data[i].freq),输出数组必须是{0,1,4,2,5,3,1,3,6,9,15}(data[data_size ].freq),没有任何排序也没有任何交换,只使用索引移动,只使用数组。
请帮我写另外两个 if 条件。
【问题讨论】:
标签: c arrays algorithm data-structures struct