ScubaDiv 编程,输出逻辑错误
Posted
技术标签:
【中文标题】ScubaDiv 编程,输出逻辑错误【英文标题】:ScubaDiv programming, logical error with outputting 【发布时间】:2018-05-04 01:30:43 【问题描述】:这个问题是关于一个潜水员或几个潜水员必须携带装有氧气和氮气的气瓶,而且气瓶有自己的重量。使用动态规划,我们必须想出一个解决方案,告诉潜水员在所需的氧和硝基下他可以获得的最佳重量(最大限度地延长潜水员在水下的时间)
输入如下:
1 //the number of divers
5 60 // ox=5 and ni=60 , the amonut of OX and NI the diver needs
5 //the number of cylinders to choose - n.
3 36 120 // 1st cyllinder => ox=3 / nit=36 / weight = 120
10 25 129 // 2nd cyllinder
5 50 250 // 3rd cyllinder
1 45 130 // 4th cyllinder
4 20 119 // 5th cyllinder
这里的输出应该是这样的:
249 //the tot weight
1 2 //cyllinders which were chosen (in this case 1st and 2nd cyllinder)
我可以找到 249,所以重量,但我正在努力了解如何获得气缸的索引,任何人都可以给我一个提示或指导我如何实现它。这是计算权重的函数:
int ox,ni,n;
int o[1000],nit[1000],w[1000];
int best[22][80],next[22][80];
int solve()
memset(best, 0x3f, sizeof(best));
best[0][0] = 0;
for (int k = 0; k < n ;k++)
memcpy(next,best,sizeof(best));
for (int i = 0; i <= ox ;i++)
for (int j = 0 ; j <= ni ;j++)
next[min(ox,i+o[k])][min(ni,j+nit[k])]= min(best[i][j]+w[k], next[min(ox,i+o[k])][min(ni,j+nit[k])]);
memcpy(best,next,sizeof(best));
cout << endl;
return best[ox][ni];
我尝试在第三个 for 循环中做出这样的 if 语句:
if (((next[min(ox,i+o[k])][min(ni,j+nit[k])]) == (best[i][j]+w[k])) && ((min(ox, i+o[k]) == ox) || (min(ni, j+nit[k])== ni) ))
cout << k << " ";
但它在大多数情况下都不起作用。谁能给我一个提示或指导我如何发表声明以捕获并打印正确的圆柱索引?
新的更新变化:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <iostream>
using namespace std;
typedef struct /* typedef for struct containing tank vals */
int ox,
nit,
wt;
tank_t;
int main()
int ndivers = 0, /* number of divers */
oxreq = 0, /* minimum oxygen required */
nitreq = 0, /* minimum nitrogen required */
n = 0, /* number of cylinders actually read */
ncyl = 0, /* number of cylinders from input file */
wtmin = INT_MAX, /* minimum weight (initialize to INT_MAX) */
*indexes = NULL; /* pointer to track tank indexes */
tank_t *tanks = NULL, best; /* pointer to tanks struct */
best.ox = 0;
/* allocate/validate storage for ncyl integers */
if ((indexes = (int*)calloc(ncyl, sizeof *indexes)) == NULL)
perror("calloc-indexes");
return 1;
/* allocate/validate storage for ncyl tanks */
if ((tanks = (tank_t*)calloc(ncyl, sizeof *tanks)) == NULL)
perror("calloc-tanks");
return 1;
cin >> ndivers;
for(int i=0; i<ndivers; i++)
cin >> oxreq >> nitreq;
cin >> ncyl;
n = ncyl;
for (int i = 0; i < ncyl; i++)
cin >> tanks[i].ox >> tanks[i].nit >> tanks[i].wt;
/* loop over each tank to use as beginning in calc */
for (int i = 0; i < n; i++)
int j = i + 1, /* set 2nd index as next tank */
*idx =(int*) calloc(n, sizeof *idx); /* allocate/zero temp index */
/* can move idx alloc out of loop & memset here */
if (!idx) /* validate allocation */
perror("calloc-idx");
return 1;
/* use a temp tank_t struct tmp to accumulate values */
tank_t tmp = tanks[i].ox, tanks[i].nit, tanks[i].wt ;
idx[i] = 1; /* set 1st index value in tmp index */
while (j < n) /* loop over remaining tanks */
idx[j] = 1; /* set next index as used */
tmp.ox += tanks[j].ox; /* add next tank ox */
tmp.nit += tanks[j].nit; /* add next tank nit */
tmp.wt += tanks[j].wt; /* add next tank wt */
/* check if total ox & nit meet min, & wt < current min */
if (tmp.ox > oxreq && tmp.nit > nitreq && tmp.wt < wtmin)
best = tmp; /* save ox, nit & wt in best */
wtmin = tmp.wt; /* update minimum wt */
memcpy(indexes, idx, n * sizeof *idx); /* copy to indexes */
memset(idx, 0, sizeof *idx * n); /* re-zero idx */
memset(&tmp, 0, sizeof tmp); /* zero tmp tank */
idx[i] = 1; /* set 1st tank index */
tmp.ox = tanks[i].ox; /* set 1st tank values */
tmp.nit = tanks[i].nit;
tmp.wt = tanks[i].wt;
j++; /* increment 2nd tank counter */
free(idx); /* free temp index */
free(tanks); /* free tanks data - done with it */
cout << best.wt;
for (int i = 0; i < n; i++)
if (indexes[i])
cout << i + 1 << " ";
free(indexes); /* free final indexes */
return 0;
【问题讨论】:
任何时候你试图将各种不同的信息作为一个“事物”来协调,你应该考虑struct
。在这里,您尝试在 3 个单独的阵列中管理 O2、N 和体重。相反,struct tank int ox, nit ,wt; ;
将允许您声明一个 struct tank
数组并使用单个索引管理所有 3 条信息。
Dan,如果您只是使用cin
,那么没有理由改用<iostream>
而不是<stdio.h>
。它将遭受匹配失败的相同陷阱。当您执行 calloc(ncyl, sizeof *indexes)
时,您的直接问题是“ncyl
的值是多少?”(分配 tanks
时遇到同样的问题)并查看:Do I cast the result of malloc?。暂时坚持使用 C —— 它会让你以后成为更好的 C++ 程序员。
@DavidC.Rankin ye 正是 ncyl 是问题所在,现在一切正常,是的,也许我应该坚持使用 C,因为在这里我了解发生的一切
干得好。我今天要跑到大学城,所以如果你难过,我会在大约 6 小时后回来。
请看:What should I do when someone answers my question?
【参考方案1】:
我不确定您在使用struct
来协调不同的坦克信息而不是尝试协调来自三个单独数组的索引的建议方面取得了多大进展。这里有一些想法和一个例子。该示例只是解决此问题的无数方法之一,也是我第一次尝试对油箱信息求和以满足最低要求ox
和nit
,同时最小化总重量。
如果油箱重量替代品碰巧提供相同的最小重量(这是您应该做的),则没有尝试最大化可用的 ox
或 nit
。
首先,正如评论中所述,只要您需要在一个数据单元上协调多条信息,您就需要考虑struct
。在您的代码中,您尝试使用以下方式管理数据:
int ox,ni,n;
int o[1000],nit[1000],w[1000];
int best[22][80],next[22][80];
虽然可行,但从“Go”这个词来看,为应该“动态”处理数据的项目分配固定存储似乎是错误的(更不用说令人困惑了)。相反,为您的 tank_type 数据使用简单的struct
,例如
typedef struct /* typedef for struct containing tank vals */
int ox,
nit,
wt;
tank_t;
(您可以使用typedef
来避免一直写stuct ...
)
好处是您现在可以为结构的no. of cylinders
分配存储空间,然后使用所有油箱值的单坐标索引访问您的数据,例如
tank_t *tanks = NULL, ...; /* pointer to tanks struct */
...
/* validate number of cylinders read from file */
if (fscanf (fp, "%d", &ncyl) != 1 || ncyl < 1)
fprintf (stderr, "error: read failed - no. of cylinders.\n");
return 1;
...
/* allocate/validate storage for ncyl tanks */
if ((tanks = calloc (ncyl, sizeof *tanks)) == NULL)
perror ("calloc-tanks");
return 1;
现在您可以简单地将您的数据读入tanks[0].ox, tanks[0].nit, ... tanks[1].ox, tanks[1].nit, ...
。
要跟踪您的坦克索引,只需分配no. of cylinders
int
,您可以将当前要比较的索引设置为1
,将剩余的索引设置为0
。 (您可以将类似的临时索引用于工作目的,并将满足您条件的当前最小坦克组合索引分配给将保存迭代结果的最终内存块)
问题的其余部分只是简单地提出对所有坦克组合进行迭代的逻辑,节省满足 ox
和 nit
标准的每个组合的权重,并将每个这样的组合与当前的最小值进行比较去。您只需要确保在实现您正在跟踪的逻辑时根据需要重置值,以便最终得到有效的比较。
(首先想到的是一组嵌套循环,类似于简单的数组排序例程,它将迭代并加在一起并比较各种组合。[毫无疑问,这是一种更有效的方法])
以下是结果,作为一种方法的示例(内联额外的 cmets 可帮助您跟进)。另请注意,我刚刚阅读了您发布的数据文件(包括 cmets),因此如果您的实际文件省略了 cmets,您可以(稍微)简化您的读取例程。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
typedef struct /* typedef for struct containing tank vals */
int ox,
nit,
wt;
tank_t;
void empty_line (FILE *fp) /* simple function to strip comments from */
/* your input file */
int c = fgetc (fp);
while (c != '\n' && c != EOF)
c = fgetc (fp);
int main (int argc, char **argv)
int ndivers = 0, /* number of divers */
oxreq = 0, /* minimum oxygen required */
nitreq = 0, /* minimum nitrogen required */
n = 0, /* number of cylinders actually read */
ncyl = 0, /* number of cylinders from input file */
wtmin = INT_MAX, /* minimum weight (initialize to INT_MAX) */
*indexes = NULL; /* pointer to track tank indexes */
tank_t *tanks = NULL, best = .ox = 0 ; /* pointer to tanks struct */
/* open file given as 1st argument or read from stdin */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
/* validate number of divers read */
if (fscanf (fp, "%d", &ndivers) != 1 || ndivers < 1)
fprintf (stderr, "error: read failed - number of divers.\n");
return 1;
empty_line (fp); /* strip remaining comments in line */
/* validate required ox and nit read from file */
if (fscanf (fp, "%d %d", &oxreq, &nitreq) != 2 ||
oxreq < 1 || nitreq < 1)
fprintf (stderr, "error: read failed - ox, nit required.\n");
return 1;
empty_line (fp);
/* validate number of cylinders read from file */
if (fscanf (fp, "%d", &ncyl) != 1 || ncyl < 1)
fprintf (stderr, "error: read failed - no. of cylinders.\n");
return 1;
empty_line (fp);
/* allocate/validate storage for ncyl integers */
if ((indexes = calloc (ncyl, sizeof *indexes)) == NULL)
perror ("calloc-indexes");
return 1;
/* allocate/validate storage for ncyl tanks */
if ((tanks = calloc (ncyl, sizeof *tanks)) == NULL)
perror ("calloc-tanks");
return 1;
/* read/validate tank information - store in tanks */
while (n < ncyl && fscanf (fp, "%d %d %d", &tanks[n].ox,
&tanks[n].nit, &tanks[n].wt) == 3)
empty_line (fp);
n++;
if (fp != stdin) fclose (fp); /* close file if not stdin */
/* loop over each tank to use as beginning in calc */
for (int i = 0; i < n; i++)
int j = i + 1, /* set 2nd index as next tank */
*idx = calloc (n, sizeof *idx); /* allocate/zero temp index */
/* can move idx alloc out of loop & memset here */
if (!idx) /* validate allocation */
perror ("calloc-idx");
return 1;
/* use a temp tank_t struct tmp to accumulate values */
tank_t tmp = tanks[i].ox, tanks[i].nit, tanks[i].wt ;
idx[i] = 1; /* set 1st index value in tmp index */
while (j < n) /* loop over remaining tanks */
idx[j] = 1; /* set next index as used */
tmp.ox += tanks[j].ox; /* add next tank ox */
tmp.nit += tanks[j].nit; /* add next tank nit */
tmp.wt += tanks[j].wt; /* add next tank wt */
/* check if total ox & nit meet min, & wt < current min */
if (tmp.ox > oxreq && tmp.nit > nitreq && tmp.wt < wtmin)
best = tmp; /* save ox, nit & wt in best */
wtmin = tmp.wt; /* update minimum wt */
memcpy (indexes, idx, n * sizeof *idx); /* copy to indexes */
memset (idx, 0, sizeof *idx * n); /* re-zero idx */
memset (&tmp, 0, sizeof tmp); /* zero tmp tank */
idx[i] = 1; /* set 1st tank index */
tmp.ox = tanks[i].ox; /* set 1st tank values */
tmp.nit = tanks[i].nit;
tmp.wt = tanks[i].wt;
j++; /* increment 2nd tank counter */
free (idx); /* free temp index */
free (tanks); /* free tanks data - done with it */
/* output results */
printf ("best tank combo that meets: O2 >= %d, N >= %d\n\n"
" O2: %d\n N : %d\n wt: %d\n\n tanks:",
oxreq, nitreq, best.ox, best.nit, best.wt);
for (int i = 0; i < n; i++)
if (indexes[i])
printf (" %d", i + 1);
putchar ('\n');
free (indexes); /* free final indexes */
return 0;
输入文件示例
$ cat dat/tank.txt
1 //the number of divers
5 60 // ox=5 and ni=60 , the amonut of OX and NI the diver needs
5 //the number of cylinders to choose - n.
3 36 120 // 1st cyllinder => ox=3 / nit=36 / weight = 120
10 25 129 // 2nd cyllinder
5 50 250 // 3rd cyllinder
1 45 130 // 4th cyllinder
4 20 119 // 5th cyllinder
使用/输出示例
$ ./bin/tankopt <dat/tank.txt
best tank combo that meets: O2 >= 5, N >= 60
O2: 13
N : 61
wt: 249
tanks: 1 2
内存使用/错误检查
在您编写的任何动态分配内存的代码中,对于分配的任何内存块,您都有 2 个职责:(1)始终保留指向起始地址的指针内存块,因此,(2) 当不再需要它时可以释放。
您必须使用内存错误检查程序来确保您不会尝试访问内存或写入超出/超出分配块的边界,尝试读取或基于未初始化的值进行条件跳转,最后,以确认您释放了已分配的所有内存。
对于 Linux,valgrind
是正常的选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序即可。
$ valgrind ./bin/tankopt <dat/tank.txt
==6126== Memcheck, a memory error detector
==6126== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==6126== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==6126== Command: ./bin/tankopt
==6126==
best tank combo that meets: O2 >= 5, N >= 60
O2: 13
N : 61
wt: 249
tanks: 1 2
==6126==
==6126== HEAP SUMMARY:
==6126== in use at exit: 0 bytes in 0 blocks
==6126== total heap usage: 7 allocs, 7 frees, 180 bytes allocated
==6126==
==6126== All heap blocks were freed -- no leaks are possible
==6126==
==6126== For counts of detected and suppressed errors, rerun with: -v
==6126== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
始终确认您已释放已分配的所有内存并且没有内存错误。
如果您还有其他问题,请告诉我。如前所述,此示例旨在提供一种用于迭代和索引跟踪的方法的示例——它并不是唯一的方法(或最有效的方法)
从stdin
添加提示和阅读
如果您仔细注意,如果文件名作为第一个参数给出,则代码已经设置为从文件读取,--或- 如果没有给出参数,则从stdin
读取.这是通过在 FILE
声明中使用三元运算符来完成的,例如:
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
三元运算符只是一个简写的if-else
,结构为(condition) ? value if true : value if false;
。所以上面(argc > 1) ? fopen (argv[1], "r") : stdin;
检查是argc > 1
,如果是这样打开argv[i]
中给出的文件名,否则它只是将stdin
分配给fp
。
知道您已经可以从 stdin
读取数据(并将 idx
的分配移到循环之外,如上面的代码 cmets 中所述),您可以执行以下操作来提示输入:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
typedef struct /* typedef for struct containing tank vals */
int ox,
nit,
wt;
tank_t;
void empty_line (FILE *fp) /* simple function to strip comments from */
/* your input file */
int c = fgetc (fp);
while (c != '\n' && c != EOF)
c = fgetc (fp);
int main (int argc, char **argv)
int ndivers = 0, /* number of divers */
oxreq = 0, /* minimum oxygen required */
nitreq = 0, /* minimum nitrogen required */
n = 0, /* number of cylinders actually read */
ncyl = 0, /* number of cylinders from input file */
wtmin = INT_MAX, /* minimum weight (initialize to INT_MAX) */
*indexes = NULL, /* pointer to track tank indexes */
*idx = NULL; /* pointer to temp index */
tank_t *tanks = NULL, best = .ox = 0 ; /* pointer to tanks struct */
/* open file given as 1st argument or read from stdin */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
if (fp == stdin) /* prompt for no. of divers */
fputs ("enter number of divers: ", stdout);
/* validate number of divers read */
if (fscanf (fp, "%d", &ndivers) != 1 || ndivers < 1)
fprintf (stderr, "error: read failed - number of divers.\n");
return 1;
empty_line (fp); /* strip remaining comments in line */
if (fp == stdin) /* prompt for no. of divers */
fputs ("enter required oxygen and nitrogen: ", stdout);
/* validate required ox and nit read from file */
if (fscanf (fp, "%d %d", &oxreq, &nitreq) != 2 ||
oxreq < 1 || nitreq < 1)
fprintf (stderr, "error: read failed - ox, nit required.\n");
return 1;
empty_line (fp);
if (fp == stdin) /* prompt for no. of divers */
fputs ("enter number of cylinders: ", stdout);
/* validate number of cylinders read from file */
if (fscanf (fp, "%d", &ncyl) != 1 || ncyl < 1)
fprintf (stderr, "error: read failed - no. of cylinders.\n");
return 1;
empty_line (fp);
/* allocate/validate storage for ncyl integers */
if ((indexes = calloc (ncyl, sizeof *indexes)) == NULL)
perror ("calloc-indexes");
return 1;
/* allocate/validate storage for ncyl tanks */
if ((tanks = calloc (ncyl, sizeof *tanks)) == NULL)
perror ("calloc-tanks");
return 1;
if (fp == stdin) /* prompt for no. of divers */
fprintf (stdout, "enter cylinder info (ox, nit, wt.) per-line:\n\n"
" enter info for cylinder[%2d]: ", n + 1);
/* read/validate tank information - store in tanks */
while (fscanf (fp, "%d %d %d", &tanks[n].ox,
&tanks[n].nit, &tanks[n].wt) == 3)
empty_line (fp);
if (++n == ncyl)
break;
if (fp == stdin) /* prompt for no. of divers */
fprintf (stdout, " enter info for cylinder[%2d]: ", n + 1);
if (fp != stdin) fclose (fp); /* close file if not stdin */
/* allocate/validate storage for temp indexes (idx) */
if ((idx = calloc (n, sizeof *idx)) == NULL)
perror ("calloc-idx");
return 1;
/* loop over each tank to use as beginning in calc */
for (int i = 0; i < n; i++)
int j = i + 1; /* set 2nd index as next tank */
memset (idx, 0, sizeof *idx * n); /* zero working index */
/* use a temp tank_t struct tmp to accumulate values */
tank_t tmp = tanks[i].ox, tanks[i].nit, tanks[i].wt ;
idx[i] = 1; /* set 1st index value in tmp index */
while (j < n) /* loop over remaining tanks */
idx[j] = 1; /* set next index as used */
tmp.ox += tanks[j].ox; /* add next tank ox */
tmp.nit += tanks[j].nit; /* add next tank nit */
tmp.wt += tanks[j].wt; /* add next tank wt */
/* check if total ox & nit meet min, & wt < current min */
if (tmp.ox > oxreq && tmp.nit > nitreq && tmp.wt < wtmin)
best = tmp; /* save ox, nit & wt in best */
wtmin = tmp.wt; /* update minimum wt */
memcpy (indexes, idx, n * sizeof *idx); /* copy to indexes */
memset (idx, 0, sizeof *idx * n); /* re-zero idx */
memset (&tmp, 0, sizeof tmp); /* zero tmp tank */
idx[i] = 1; /* set 1st tank index */
tmp.ox = tanks[i].ox; /* set 1st tank values */
tmp.nit = tanks[i].nit;
tmp.wt = tanks[i].wt;
j++; /* increment 2nd tank counter */
free (idx); /* free temp index */
free (tanks); /* free tanks data - done with it */
/* output results */
printf ("\nbest tank combo that meets: O2 >= %d, N >= %d\n\n"
" O2: %d\n N : %d\n wt: %d\n\n tanks:",
oxreq, nitreq, best.ox, best.nit, best.wt);
for (int i = 0; i < n; i++)
if (indexes[i])
printf (" %d", i + 1);
putchar ('\n');
free (indexes); /* free final indexes */
return 0;
使用/输出示例(从带提示的标准输入读取)
$ ./bin/tankopt2
enter number of divers: 1
enter required oxygen and nitrogen: 5 60
enter number of cylinders: 5
enter cylinder info (ox, nit, wt.) per-line:
enter info for cylinder[ 1]: 3 36 120
enter info for cylinder[ 2]: 10 25 129
enter info for cylinder[ 3]: 5 50 250
enter info for cylinder[ 4]: 1 45 130
enter info for cylinder[ 5]: 4 20 119
best tank combo that meets: O2 >= 5, N >= 60
O2: 13
N : 61
wt: 249
tanks: 1 2
【讨论】:
非常感谢,一个很好的解释,也许我错了没有提到输入将来自键盘而不是来自文件,我只是在我的问题中评论了输入以了解它是如何去。现在我更改了您的代码,看看它是否适用于我从键盘输入,但我遇到了一些我无法正确调试的内存问题!你能帮我一点吗? 当然。在问题的末尾添加您当前的代码和错误,我会看看您在哪里遇到问题。如果您只是添加所需信息的提示并将fscanf
更改为scanf
,它应该可以正常工作。
我实际上是在尝试将所有内容都切换到 c++ 中,直到现在我只是更改了输入/输出,但我可能在某处发生了内存泄漏,看上面我刚刚发布了代码,它编译但之后我输入的数据出现内存错误
好的,除非您使用vector <tank_t>
,否则迁移到C++ 并使用new
和delete
没有任何好处(C++ 实际上会使流处理复杂一点)跨度>
以上是关于ScubaDiv 编程,输出逻辑错误的主要内容,如果未能解决你的问题,请参考以下文章