- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这个问题与潜水员或许多潜水员有关,这些潜水员必须带入装有氧气和氮气的钢瓶,钢瓶也有自重。使用动态编程,我们必须提供一种解决方案,该解决方案告诉潜水员使用所需的Oxy和Nitro可获得最佳重量(以最大化潜水员在水下的时间)
输入如下:
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)
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];
}
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
来协调坦克信息的不同部分,而不是尝试从三个单独的数组协调索引的建议,您取得了多少进展。这里有一些想法和示例。该示例只是多种解决方案中的一种,并且是我的第一个切入点,即对 jar 信息进行求和以达到所需的最小ox
和nit
,同时最大程度地降低总重量。
如果储 jar 重量的替代物碰巧提供了相同的最小重量,则不会尝试使ox
或nit
最大化(这是您应该做的)
首先,如评论中所述,只要您需要在一条数据单元上协调多条信息,就需要考虑struct
。在您的代码中,您尝试使用以下方法管理数据:
int ox,ni,n;
int o[1000],nit[1000],w[1000];
int best[22][80],next[22][80];
struct
,例如
typedef struct { /* typedef for struct containing tank vals */
int ox,
nit,
wt;
} tank_t;
typedef
来避免始终写
stuct ...
)
no. of cylinders
分配存储空间,然后使用所有储 jar 值的单坐标索引访问数据,例如
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
。 (您可以将类似的临时索引用于工作目的,并将满足条件的当前最小储 jar 组合索引分配给将保留迭代结果的最终内存块)
ox
和
nit
标准的每种组合的重量,并将每种组合与当前的最小数量进行比较。您只需要确保在实现逻辑时就可以根据需要重置值,从而获得有效的比较。
#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
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
的分配移到循环外),您可以执行类似以下操作的提示输入:
#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
关于c++ - ScubaDiv编程,输出时出现逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50165900/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!