473,805 Members | 2,059 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: cutting sticks problem

On May 7, 11:24*pm, sophia <sophia.ag...@g mail.comwrote:
The cutting sticks problem---given a stick of length L and a set of
points where it has to be cut. If the cost of making a cut is equal to
the length of the stick, what is the best algorithm to find the
optimal sequence of cuts(giving minimum cost)
Contrary to a suggestion in this thread,
the straightforward solution to this puzzle
is not of exponential complexity, but rather N^3/3.
Yes, I know O(N^3) = O(N^3/3) but I show the constant
divisor to emphasize that the iterative structure is
related to the volume of a pyramid.

I'm enclosing my source code (and cross-posting to
comp.lang.c) for critique. The program is *not*
thoroughly tested; I estimate it still has 1.84 bugs.
(Certain peculiar code layout details are to ensure
short lines for Usenet.)

/* begin bestcutter.c */
#include <stdlib.h>
#include <stdio.h>

#define MAXPIECE 100

/* Sol[a][b] describes substick [a ... a+b+1] */
struct {
double cost, leng;
int cutpt;
} Sol[MAXPIECE-1][MAXPIECE];

int bestcut(int xbeg, int xend)
{
int x, bstc;
double xcost, cheapest = 99999999;

for (x = xbeg + 1; x < xend; x++) {
xcost =
Sol[xbeg][x - xbeg - 1].cost
+ Sol[x][xend - x - 1].cost;
if (xcost < cheapest)
cheapest = xcost, bstc = x;
}
return bstc;
}

double mkcuts(int xbeg, int ncut)
{
int cutpt;
double tcost;

if (ncut < 1)
return 0;
cutpt = Sol[xbeg][ncut].cutpt;
tcost = Sol[xbeg][ncut].leng;
printf("Making cut at mark %d cost = %f\n",
cutpt, tcost);
return tcost
+ mkcuts(xbeg, cutpt - xbeg - 1)
+ mkcuts(cutpt, xbeg + ncut - cutpt);
}

int main(int argc, char **argv)
{
int ncut, ix1, bstc;

if (MAXPIECE + 1 < argc || argc < 2) {
printf("Usage: cutstick #L1 #L2 ... #LN\n");
printf(" where #Lk is the distance from k-1'th");
printf(" mark to k'th mark.\n (0'th and N'th");
printf(" marks are stick ends.) N <= %d.\n",
MAXPIECE);
return EXIT_FAILURE;
}
for (ix1 = 0; ix1 < argc - 1; ix1++)
Sol[ix1][0].leng = atof(argv[ix1 + 1]);
for (ncut = 1; ncut < argc - 1; ncut++)
for (ix1 = 0; ix1 < argc - ncut + 1; ix1++)
if (ncut == 1) {
Sol[ix1][ncut].cutpt = ix1 + 1;
Sol[ix1][ncut].cost =
Sol[ix1][ncut].leng =
Sol[ix1][0].leng
+ Sol[ix1 + 1][0].leng;
} else {
Sol[ix1][ncut].leng =
Sol[ix1][0].leng
+ Sol[ix1 + 1][ncut - 1].leng;
Sol[ix1][ncut].cutpt =
bstc = bestcut(ix1, ix1 + ncut + 1);
Sol[ix1][ncut].cost =
Sol[ix1][ncut].leng
+ Sol[ix1][bstc - ix1 - 1].cost
+ Sol[bstc][ncut - bstc + ix1].cost;
}
printf("Total cost = %f\n", mkcuts(0, argc - 2));
return EXIT_SUCCESS;
}
/* end bestcutter.c */
/* Sample execution:
* % bestcutter 2 3 1 5
* Making cut at mark 3 cost = 11.000000
* Making cut at mark 1 cost = 6.000000
* Making cut at mark 2 cost = 4.000000
* Total cost = 21.000000
*/

James Dow Allen
Jun 27 '08 #1
6 3642
On Fri, 9 May 2008 03:48:20 -0700 (PDT), James Dow Allen
<jd*********@ya hoo.comwrote:
>On May 7, 11:24*pm, sophia <sophia.ag...@g mail.comwrote:
>The cutting sticks problem---given a stick of length L and a set of
points where it has to be cut. If the cost of making a cut is equal to
the length of the stick, what is the best algorithm to find the
optimal sequence of cuts(giving minimum cost)

Contrary to a suggestion in this thread,
the straightforward solution to this puzzle
is not of exponential complexity, but rather N^3/3.
Yes, I know O(N^3) = O(N^3/3) but I show the constant
divisor to emphasize that the iterative structure is
related to the volume of a pyramid.

I'm enclosing my source code (and cross-posting to
comp.lang.c) for critique. The program is *not*
thoroughly tested; I estimate it still has 1.84 bugs.
(Certain peculiar code layout details are to ensure
short lines for Usenet.)

/* begin bestcutter.c */
[snip code]
>
James Dow Allen
I think that you could use a better algorithm. You are repeatedly
calculating the cost of the same sticks as part of your subproblems.
If there is a stick with marks at a, b, c, ... x, y, z then if you
make the first cut as a and the second cut at z you are left with a
stick of length z-a with cuts at b, c, ... x, y. If you make the
first cut at z and the second cut at a then you will have exactly the
same subproblem to solve. Saving the result and retrieving it would
be much faster than re-solving a problem you had already solved. This
needs more memory than the simple algorithm of course.

It would probably not be worthwhile storing intermediate results for
0, 1 or 2 cuts since there is no choice possible for 0 or 1 cuts and
there is an obvious algorithm for 2 cuts (cut off the longer
end-piece). I am not sure if there is an easy algorithm for three
cuts, not having thought about it at any length.

rossum

Jun 27 '08 #2
On May 11, 3:49*pm, rossum <rossu...@coldm ail.comwrote:
On Fri, 9 May 2008 03:48:20 -0700 (PDT), James Dow Allen
<jdallen2...@ya hoo.comwrote:
the straightforward solution to this puzzle
is not of exponential complexity, but rather N^3/3.
I'm enclosing my source code (and cross-posting to
comp.lang.c) for critique.
I think that you could use a better algorithm. *You are repeatedly
calculating the cost of the same sticks as part of your subproblems.
No. Reread the source to see that the code calculates and saves the
intermediate results exactly as you describe. It is the caller of
bestcut()
rather than bestcut() itself that saves these results -- is that
where your confusion lies?

My algorithm is O(N^3). Are your comments intended to suggest
existence of a less complex algorithm?

James
Jun 27 '08 #3
On Sun, 11 May 2008 02:51:38 -0700 (PDT), James Dow Allen
<jd*********@ya hoo.comwrote:
>On May 11, 3:49*pm, rossum <rossu...@coldm ail.comwrote:
>On Fri, 9 May 2008 03:48:20 -0700 (PDT), James Dow Allen
<jdallen2...@y ahoo.comwrote:
>the straightforward solution to this puzzle
is not of exponential complexity, but rather N^3/3.
>I'm enclosing my source code (and cross-posting to
comp.lang.c) for critique.
>I think that you could use a better algorithm. *You are repeatedly
calculating the cost of the same sticks as part of your subproblems.

No. Reread the source to see that the code calculates and saves the
intermediate results exactly as you describe.
It does indeed, my mistake. Thankyou for the correction.
>It is the caller of
bestcut()
rather than bestcut() itself that saves these results -- is that
where your confusion lies?
Probably because I am more used to Java rather than C, and your
solution is expressed in procedural rather than OO terms.
>
My algorithm is O(N^3). Are your comments intended to suggest
existence of a less complex algorithm?
No. Since I thought you were recalculating intermediate results I
thought there was an obvious speed improvement that wasn't actually
there.

Apologies for my mistake.

rossum
>
James
Jun 27 '08 #4
On May 11, 6:44*pm, rossum <rossu...@coldm ail.comwrote:
On Sun, 11 May 2008 02:51:38 -0700 (PDT), James Dow Allen wrote
No. *Reread the source to see that the code calculates and saves the
intermediate results exactly as you describe.

It does indeed, my mistake. *Thankyou for the correction.
Thank *you* for bringing closure to this subthread.
Everyone can (and does) make mistakes. *Acknowledging*
a mistake, especially in these newsgroups, is as rare
as spotting a beautiful butterfly on a stormy day.
Apologies for my mistake.
I think mine was the bigger mistake. A few well chosen
comments in the source would have prevented any
confusion.

James
Jun 27 '08 #5
On May 11, 2:51*am, James Dow Allen <jdallen2...@ya hoo.comwrote:
>
My algorithm is O(N^3). *Are your comments intended to suggest
existence of a less complex algorithm?
I'm unclear why the program has a complexity of N^3 instead of N!
(which is the number of ways in which the stick can be cut.)

Greg

Jun 27 '08 #6
On Sun, 11 May 2008 23:27:41 -0700 (PDT), Greg Herlihy
<gr****@mac.com wrote:
>On May 11, 2:51*am, James Dow Allen <jdallen2...@ya hoo.comwrote:
>>
My algorithm is O(N^3). *Are your comments intended to suggest
existence of a less complex algorithm?

I'm unclear why the program has a complexity of N^3 instead of N!
(which is the number of ways in which the stick can be cut.)

Greg
I am sure James has a more detailed answer, but basically James'
algorithm saves intermediate results so that duplicates among your N!
possibilities are saved and not recalculated. For example on a stick
with cuts at a, b, c, ... x, y, z there will be at some point the need
to calculate the best way to cut the substick f, g, h, i , j. Once
that substick has been calculated for the first time, if the result is
stored then that result can be retrieved in constant time (array
access in James' program) which reduces the run time of the algorithm
greatly. The 5 cut substick is encountered 21! times, only one of
which needs to be calculated.

rossum

Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3719
by: Liberal | last post by:
I am looking for the simplest forum, bbs script which has those features? new messages will be displayed only after the administrator reviewed allow users post without signing up display the newest message first. prefer perl, but php is ok.
2
1420
by: Jay | last post by:
I have a form on asp page that pulls info from a DB when the page loads. It them puts the info into text boxes on the page that are editable by the user. The only problem I have is say in the description text box it should read "HP Laserjet 5Si" , it always cuts the text off where it just says "HP" .. It does this on all the text boxes? I can't seem to figure out why it is doing it. Here is the sample code: With quotes around <%=...
1
1334
by: Abe Frohnman | last post by:
Hey all, I have another task I'm trying to find the solution for. I have a text box that I want to cut and paste text into, from a menu. This is the code I have so far: private void menuItem6_Click(object sender, System.EventArgs e) { if (textBoxDescription.ContainsFocus) {
7
1502
by: mmarlow | last post by:
Hi all, I wish I knew if this was even a PHP problem or not! It's probably Internet Explorer but here goes anyway... Random pages at random times don't appear correctly in IE6, the HTML is actually cut short at seemingly random points (it's very random, you know). It could be at any character on any line. This is usually displayed simply as a background with no content, but viewing the source actually shows quite a lot, although sometimes...
8
2087
by: Paul | last post by:
Hi all, I'm probably missing something obvious here, but occasionally the response stream for pages on my site is cutting off leaving incomplete HTML and an ugly page. Response.Buffer is set to true - is there anything else that would be causing this? I'm using ASP .NET 2.0 on a Win 2K3 box.
2
1374
by: Winger | last post by:
Hi, I'm using a HttpWebRequest/HttpWebResponse to get plain html code off a website. This is the code: (...) Dim Resp As HttpWebResponse Try Resp = CType(request.GetResponse(), HttpWebResponse)
4
2735
by: Matt Haggard | last post by:
I'm using PIL (Python Imaging Library) to generate button images. They consist of a left end image, a middle, repeating image and a right side image.... anyway, that's not important I'm using a TTF font for the text of the button (Verdana.TTF) and it keeps cutting the bottom part of the the g's q's and y's off. Here's the important parts of my code (options contains command-line params):
0
1009
by: Joseph king | last post by:
well so far the problem for me is not the linking i have a kinda good code for that. here is a little snippet of the idea that i used on an old version that split the picture without input from the user. #this code defines that the edges have a place on the grid. def join_point(self, type): orect = self.orig_image.get_rect() if type == "north": return ((orec.width/2, 20))
5
2129
by: Roger | last post by:
I have a siebel crm application thats cutting and archiving logs every minute. Here is the db cfg Log buffer size (4KB) (LOGBUFSZ) = 512 Log file size (4KB) (LOGFILSIZ) = 15000 Number of primary log files (LOGPRIMARY) = 30 Number of secondary log files (LOGSECOND) = 40 Group commit count (MINCOMMIT) = 1 How can I reduce the number of...
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10369
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.