Форум программистов, компьютерный форум, киберфорум
Алгоритмы
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.67/18: Рейтинг темы: голосов - 18, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 15.04.2022
Сообщений: 4

Разрезы прямоугольника на детали без отходов

15.04.2022, 13:29. Показов 4525. Ответов 24

Студворк — интернет-сервис помощи студентам
Необходимо разрезать прямоугольник размера x × y на детали прямоугольной формы размера x1 × y1 и x2 × y2, чтобы отходы были минимальными. Возможны только вертикальные и горизонтальные разрезы. Т. е. после первого разреза получается два прямоугольника, которые впоследствии также можно разрезать.

Формат входных данных
На входе содержится шесть целых чисел x, y, x1, y1, x2, y2 (1 ≤ x, y ≤ 300, 1 ≤ x1, x2 ≤ x, 1 ≤ y1, y2 ≤ y).
Формат выходных данных
Выведите минимальную сумму площадей остатков.
Пример входных данных 10 10 2 9 3 4
Ответ 10
Помогите пожалуйста решить, я понимаю примерно что нужно делать но не могу даже составить рекуррентное соотношение.
Задача должна решаться через динамическое программирование.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
15.04.2022, 13:29
Ответы с готовыми решениями:

Построить третье изображение детали по двум данным, дать разрезы, построить натуральный вид наклонного сечения
Построить третье изображение детали по двум данным, дать разрезы, построить натуральный вид наклонного сечения, а также наглядное...

Два прямоугольника заданы координатами своих вершин. Определите, параллельны ли стороны одного прямоугольника сторонам другого прямоугольника.
1 Два прямоугольника заданы координатами своих вершин. Определите, параллельны ли стороны одного прямоугольника сторонам другого...

Нахождение количества точек внутри прямоугольника, на границе прямоугольника, вне прямоугольника
Как найти количество точек внутри прямоугольника, на границе прямоугольника, вне прямоугольника. Дан массив со случайными числами: x (...

24
6180 / 945 / 313
Регистрация: 25.02.2011
Сообщений: 1,381
Записей в блоге: 1
22.04.2022, 08:29
Студворк — интернет-сервис помощи студентам
TheCalligrapher, огромное спасибо, что дали описание и поделились кодом
Буду изучать эту тему дальше, есть что еще улучшать

То что я выложил здесь придумывал самостоятельно.
А учитывая,
Цитата Сообщение от TheCalligrapher Посмотреть сообщение
надо заметить, решает это задачу намного быстрее. Тоже с нулевым отходом и менее эклектичным результатом
У меня получилось даже не плохо, причем считает не очень долго даже на интерпретируемом языке.

Также были собственные наработки по задаче 2DSP (упаковка в луограниченную полосу)
Если будет время, посмотрите примеры с решением, на сколько эффективны получились раскрои?
Вложения
Тип файла: xlsx 2DSP.xlsx (254.6 Кб, 29 просмотров)
0
Вездепух
Эксперт CЭксперт С++
 Аватар для TheCalligrapher
13215 / 6847 / 1826
Регистрация: 18.10.2014
Сообщений: 17,347
22.04.2022, 22:59
Цитата Сообщение от m-ch Посмотреть сообщение
Цитата Сообщение от TheCalligrapher
надо заметить, решает это задачу намного быстрее. Тоже с нулевым отходом и менее эклектичным результатом
У меня получилось даже не плохо, причем считает не очень долго даже на интерпретируемом языке.
Да, без сомнения. Однако надо заметить, что ситуации, которые допускают "идеальное" гильотинное заполнение на самом деле являются более простыми, чем ситуации с ненулевым отходом. Хотя интуитивно кажется наоборот: идеальную укладку найти труднее, чем укладку "абы как"

Вот та статья P.Y.Wang, которую я упомянул выше, посвящена не столько теме построения гильотинных раскроев через попарное слияние, сколько теме ускорения такого подхода через применение всяких приблизительных приемов. А именно, в статье идет речь просто-напросто о раннем отсеве тех промежуточных конфигураций, которые содержат слишком высокий процент внутреннего отхода. Выполнение такого отсева приводит к существенному ускорению процесса перебора, но, разумеется, как только мы вводим такой промежуточный отсев, мы уже не можем гарантировать, что найдем оптимальное решение в общем случае.

Однако если задача допускает "идеальное" гильотинное решение, то такое решение не будет утеряно в процессе такого отсева.

Например, предыдущая версия моего кода, как я писал выше, на моей машине решает задачу 300 300 3 3 17 5 13 7 11 в течение ~5 минут. Новая многопоточная версия на той же машине (6 ядер x 2 = 12 потоков) решает ту же задачу за ~40 секунд. А вот если полностью запретить отходы, т.е. ограничить перебор только идеальными безотходными комбинациями, то задача решается за ~10 секунд.

Поэтому для настоящего тестирования таких алгоритмов нужны именно хитро построенные наборы входных данных, на которых как ни верти, но отход получается относительно большим. Строить такие примеры - нетривиальная задача. То есть маленький пример с большим отходом построить несложно, но маленькие примеры непоказательны. А вот как построить большой пример - не ясно...
0
6180 / 945 / 313
Регистрация: 25.02.2011
Сообщений: 1,381
Записей в блоге: 1
05.05.2022, 17:32
Сделал два алгоритма расчета: быстрый - тот, который я использовал ранее, и предложенный алгоритм от TheCalligrapher (в моей интерпретации на VBA)

Первый считает быстро, но, как правило, не находит идеальное решение
Второй очень сильно подает в скорости при увеличении размеров прямоугольников, но на малых размерностях считает хорошо.
Вложения
Тип файла: rar 2D Dynamic.rar (122.5 Кб, 11 просмотров)
0
Вездепух
Эксперт CЭксперт С++
 Аватар для TheCalligrapher
13215 / 6847 / 1826
Регистрация: 18.10.2014
Сообщений: 17,347
05.05.2022, 18:32
Я тут тем временем сделал многопоточную версию кода, а также добавил ограничение на допустимый внутренний отход в процессе генерации промежуточных решений, как это сделано в алгоритмах из статьи P.Y.Wang. Теперь входные параметры можно указывать на выбор в командной строке или в стандартном вводе, а также поддерживаются параметры

Code
1
2
3
-waste_abs=<процент>
-waste_rel=<процент>
-waste=<площадь>
которые и задают это ограничение на допустимый отход. waste_abs - процент от площади палеты, waste_rel - процент от площади промежуточного решения, waste - просто конкретное значение площади.

Наиболее свежий вариант кода, все еще в работе
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <bit>
#include <span>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <thread>
#include <stdexcept>
#include <iomanip>
#include <fstream>
#include <chrono>
#include <sstream>
#include <iostream>
 
#ifdef _MSC_VER
  #pragma warning(disable : 4146 4245 4189 4100)
#endif // _MSC_VER
 
#define noEXTRA_STATS
#define noDUMP_GDS
 
#ifdef EXTRA_STATS
  #define EXTRA_STATS_ONLY(x) x
#else // EXTRA_STATS
  #define EXTRA_STATS_ONLY(x)
#endif // EXTRA_STATS
 
//////////////////////////////////////////////////////////////////////////////////////////
 
using Size = unsigned;
using Area = unsigned;
 
//////////////////////////////////////////////////////////////////////////////////////////
 
template <typename T> std::size_t hash_mix(std::size_t hash, T v)
{
  return std::rotl(hash, 1) ^ std::hash<T>()(v);
}
 
class Rect
{ 
  Size dx_, dy_; 
  Area area_;
 
public:
  Rect() = default;
  Rect(Size dx, Size dy) : dx_(dx), dy_(dy), area_(dx * dy)
    {}    
 
  Size dx() const
    { return dx_; }
 
  Size dy() const
    { return dy_; }
 
  Area area() const
    { return area_; }
 
  bool is_horizontal() const
    { return dx_ > dy_; }
 
  void flip()
    { std::swap(dx_, dy_); }
 
  bool fits(const Rect &limits) const
    { return dx_ <= limits.dx_ && dy_ <= limits.dy_; }
 
  friend Rect horizontal_composition(const Rect &lhs, const Rect &rhs)
    { return { lhs.dx_ + rhs.dx_, std::max(lhs.dy_, rhs.dy_) }; }
 
  friend Rect vertical_composition(const Rect &lhs, const Rect &rhs)
    { return { std::max(lhs.dx_, rhs.dx_), lhs.dy_ + rhs.dy_ }; }
 
  friend Rect horizontal_waste(const Rect &lhs, const Rect &rhs)
  { 
    if (lhs.dy_ < rhs.dy_)
      return { lhs.dx_, rhs.dy_ - lhs.dy_ };
    else
      return { rhs.dx_, lhs.dy_ - rhs.dy_ };
  }
    
  friend Rect vertical_waste(const Rect &lhs, const Rect &rhs)
  {
    if (lhs.dx_ < rhs.dx_)
      return { rhs.dx_ - lhs.dx_, lhs.dy_ };
    else
      return { lhs.dx_ - rhs.dx_, rhs.dy_ };
  }
 
  struct Hash
  {
    std::size_t operator ()(const Rect &r) const
      { return hash_mix(hash_mix(0, r.dx_), r.dy_); }
  };
 
  friend bool operator ==(const Rect &lhs, const Rect &rhs)
    { return lhs.dx_ == rhs.dx_ && lhs.dy_ == rhs.dy_; }
 
  friend std::istream &operator >>(std::istream &strm, Rect &rhs)
  {
    if (!(strm >> rhs.dx_ >> rhs.dy_))
      throw std::invalid_argument("invalid rectangle size");
    return strm;
  }
 
  friend std::ostream &operator <<(std::ostream &strm, const Rect &rhs)
    { return strm << rhs.dx_ << 'x' << rhs.dy_; }
};
 
enum class Composition
{
  ORIGINAL,
  HORIZONTAL,
  VERTICAL
};
 
struct PatternDesc
{
  Area waste = std::numeric_limits<Area>::max();
 
  mutable std::size_t index;
 
#ifdef DUMP_GDS
  unsigned id;
  Composition composition = Composition::ORIGINAL;
  Rect key_a, key_b; // Patterns::const_iterator it_a, it_b;
  mutable bool is_dumped = false;
#endif // DUMP_GDS
};
 
using Patterns = std::unordered_map<Rect, PatternDesc, Rect::Hash>;
using Pattern = Patterns::value_type;
 
#ifdef EXTRA_STATS
 
struct ExtraStats
{
  std::size_t n_compositions; 
 
  std::size_t n_patterns_built; 
  // Passed size and waste limits
 
  std::size_t n_patterns_updated; 
  // Accepted as updates to previously known patterns
 
  ExtraStats &operator +=(const ExtraStats &rhs) noexcept
  {
    n_compositions += rhs.n_compositions;
    n_patterns_built += rhs.n_patterns_built;
    n_patterns_updated += rhs.n_patterns_updated;
    return *this;
  }
};
 
#endif // EXTRA_STATS
 
struct Context
{
  unsigned n_threads = std::thread::hardware_concurrency();
 
  Rect limits;
 
  unsigned allowed_waste_perc = 100;
  Area allowed_waste = std::numeric_limits<Area>::max();
  bool is_absolute_waste = true;
 
  std::vector<Rect> originals;
  Area min_original_area = std::numeric_limits<Area>::max();
 
  EXTRA_STATS_ONLY(ExtraStats extra_stats;)
 
  void postprocess()
  {
    if (allowed_waste_perc == -1)
    { // Absolute value 'allowed_waste' is already set
      assert(is_absolute_waste);
      return;
    }
 
    // Percentage value is set, 'allowed_waste' is not
 
    if (allowed_waste_perc == 0)
    {
      allowed_waste = 0;
      is_absolute_waste = true;
    }
    else if (allowed_waste_perc == 100)
    {
      allowed_waste = std::numeric_limits<Area>::max();
      is_absolute_waste = true;
    }
    else if (is_absolute_waste)
      allowed_waste = limits.area() * allowed_waste_perc / 100;
  }
 
  bool fits_limits(const Rect &box) const
    { return box.fits(limits); }
 
  bool is_allowed_waste(Area waste, const Rect &box) const
  { 
    if (is_absolute_waste)
      return waste <= allowed_waste;
 
    assert(allowed_waste_perc > 0 && allowed_waste_perc < 100);
    return waste <= box.area() * allowed_waste_perc / 100;
  }
 
  bool encloses_original(const Rect &box) const
  {
    Area area = box.area();
    if (area < min_original_area)
      return false;
 
    for (const Rect &original : originals)
    {
      if (original.fits(box))
        return true;
 
      if (area < original.area())
        break;
    }
 
    return false;
  }
 
  Area total_waste(const Pattern &pattern) const
  {
    const Rect &box = pattern.first;
    const PatternDesc &desc = pattern.second;
    assert(box.area() <= limits.area()); 
    return limits.area() - box.area() + desc.waste;
  }
};
 
struct ThreadContext
{
  std::thread thread;
  EXTRA_STATS_ONLY(ExtraStats extra_stats;)
};
 
void combine(const Pattern &a, const Pattern &b, 
             const Patterns &all_patterns, Patterns &new_patterns,
             const Context &context, ThreadContext &thread_context)
{
  const Rect &box_a = a.first, &box_b = b.first;
  const PatternDesc &desc_a = a.second, &desc_b = b.second;
 
  EXTRA_STATS_ONLY(++thread_context.extra_stats.n_compositions);
 
  for (Composition composition : { Composition::HORIZONTAL, Composition::VERTICAL })
  {
    Rect box = composition == Composition::HORIZONTAL ?
      horizontal_composition(box_a, box_b) : vertical_composition(box_a, box_b);
 
    assert(box_a.area() + box_b.area() <= box.area());
 
    if (!context.fits_limits(box))
      continue;
 
    Rect new_waste_box = composition == Composition::HORIZONTAL ?
      horizontal_waste(box_a, box_b) : vertical_waste(box_a, box_b);
 
    Area new_waste = new_waste_box.area();
    assert(box.area() == box_a.area() + box_b.area() + new_waste);
 
    Area waste = new_waste + desc_a.waste + desc_b.waste;
    assert(waste < box.area());
 
    if (new_waste > 0)
    { // Otherwise there's no point in checking against allowable waste since waste 
      // percentage could only decrease
      if (!context.is_allowed_waste(waste, box))
        continue;
 
      if (context.encloses_original(new_waste_box))
        continue;
    }
 
    EXTRA_STATS_ONLY(++thread_context.extra_stats.n_patterns_built);
 
    Patterns::const_iterator it = all_patterns.find(box);
    if (it != all_patterns.end())
    {
      const PatternDesc &desc = it->second;
      if (waste >= desc.waste)
        continue;
    }
 
    // New or better pattern
 
    PatternDesc &new_desc = new_patterns[box];
    if (waste >= new_desc.waste)
      continue;
 
    new_desc.waste = waste;
 
#ifdef DUMP_GDS
    static unsigned i_desc_id;
    new_desc.id = ++i_desc_id; 
    new_desc.composition = composition;
    new_desc.key_a = box_a;
    new_desc.key_b = box_b;
#endif // DUMP_GDS
 
    EXTRA_STATS_ONLY(++thread_context.extra_stats.n_patterns_updated);
  }
}
 
using ItsUpdated = std::vector<Patterns::const_iterator>;
using ItsUpdatedSpan = std::span<Patterns::const_iterator>;
 
void generate_new_patterns(ItsUpdatedSpan its_updated, const Patterns &all_patterns, 
                           Patterns &new_patterns, 
                           const Context &context, ThreadContext &thread_context)
{
  // Patterns from 'its_updated' have 'PatternDesc::index' values assigned to them. All 
  // other patterns have zero in that field 
 
  for (Patterns::const_iterator it_a : its_updated)
  {
    const Pattern &a = *it_a;
    assert(a.second.index > 0);
 
    for (const Pattern &b : all_patterns)
      if (a.second.index >= b.second.index)
        // The comparison ensures that we combine updated-to-old unconditionally, and 
        // updated-to-updated only one way
        combine(a, b, all_patterns, new_patterns, context, thread_context);
  }
}
 
void merge_new_patterns(Patterns &dst_patterns, Patterns &src_patterns, 
                        ItsUpdated *its_updated = nullptr)
{
  while (!src_patterns.empty())
  {
    Patterns::iterator it_src = src_patterns.begin();
    const Rect &src_box = it_src->first;
    const PatternDesc &src_desc = it_src->second;
    // These should remain valid during extraction-insertion of the node
 
    Patterns::node_type node = src_patterns.extract(it_src);
    auto ir = dst_patterns.insert(std::move(node));
 
    assert(ir.position->first == src_box);
    PatternDesc &dst_desc = ir.position->second;
 
    if (!ir.inserted)
    {
      if (src_desc.waste >= dst_desc.waste)
        continue;
 
      dst_desc.waste = src_desc.waste;
    }
 
    assert(dst_desc.waste == src_desc.waste);
 
    if (its_updated != nullptr)
    {
      assert(dst_desc.index == 0);
      its_updated->push_back(ir.position);
      dst_desc.index = its_updated->size();
    }
  }
}
 
//////////////////////////////////////////////////////////////////////////////////////////
 
#ifdef DUMP_GDS
 
void dump_gds_sname(std::ofstream &f, Patterns::const_iterator it_cell)
{
  const Rect &box = it_cell->first;
  const PatternDesc &desc = it_cell->second;
  f << (desc.composition == Composition::ORIGINAL ? "Box_" : "Pattern_") << 
    desc.id << "_" << box;
}
 
void dump_gds_rect(std::ofstream &f, unsigned layer, const Rect &r)
{
  f << "BOUNDARY" << std::endl;
  f << "LAYER " << layer << std::endl;
  f << "DATATYPE 0" << std::endl;
  f << "XY 0:0" << std::endl;
  f << r.dx() << ":0" << std::endl;
  f << r.dx() << ":" << r.dy() << std::endl;
  f << "0:" << r.dy() << std::endl;
  f << "0:0" << std::endl;
  f << "ENDEL" << std::endl;
}
 
void dump_gds_cell(std::ofstream &f, Patterns::const_iterator it_cell, 
                   const Patterns &all_patterns)
{
  const Rect &box = it_cell->first;
  const PatternDesc &desc = it_cell->second;
 
  if (desc.is_dumped)
    return;
 
  desc.is_dumped = true;
 
  f << "BGNSTR 1/1/2022 00:00:00 1/1/2022 00:00:00" << std::endl;
  f << "STRNAME "; dump_gds_sname(f, it_cell); f << std::endl;
 
  Patterns::const_iterator it_sub_cell_a, it_sub_cell_b;
 
  if (desc.composition == Composition::ORIGINAL)
    dump_gds_rect(f, desc.id, box);
  else
  {
    it_sub_cell_a = all_patterns.find(desc.key_a);
    it_sub_cell_b = all_patterns.find(desc.key_b);
    assert(it_sub_cell_a != all_patterns.end() && it_sub_cell_b != all_patterns.end());
 
    f << "SREF" << std::endl;
    f << "SNAME "; dump_gds_sname(f, it_sub_cell_a); f << std::endl;
    f << "XY 0:0" << std::endl;
    f << "ENDEL" << std::endl;
 
    f << "SREF" << std::endl;
    f << "SNAME "; dump_gds_sname(f, it_sub_cell_b); f << std::endl;
 
    if (desc.composition == Composition::HORIZONTAL)
      f << "XY " << it_sub_cell_a->first.dx() << ":0" << std::endl;
    else
      f << "XY 0:" << it_sub_cell_a->first.dy() << std::endl;
 
    f << "ENDEL" << std::endl;
  }
 
  f << "ENDSTR" << std::endl << std::endl;
 
  if (desc.composition != Composition::ORIGINAL)
  {
    dump_gds_cell(f, it_sub_cell_a, all_patterns);
    dump_gds_cell(f, it_sub_cell_b, all_patterns);
  }
}
 
void dump_gds(const char *file, Patterns::const_iterator it_root, 
              const Patterns &all_patterns, const Context &context)
{
  std::ofstream f(file);
  if (!f)
    return;
 
  f << "HEADER 600" << std::endl;
  f << "BGNLIB 1/1/2022 00:00:00 1/1/2022 00:00:00" << std::endl;
  f << "LIBNAME " << context.limits << std::endl;
  f << "UNITS 0.001 1e-09" << std::endl << std::endl;
 
  f << "BGNSTR 1/1/2022 00:00:00 1/1/2022 00:00:00" << std::endl;
  f << "STRNAME Result_" << context.limits << std::endl;
  dump_gds_rect(f, 0, context.limits);
  f << "SREF" << std::endl;
  f << "SNAME "; dump_gds_sname(f, it_root); f << std::endl;
  f << "XY 0:0" << std::endl;
  f << "ENDEL" << std::endl;
  f << "ENDSTR" << std::endl << std::endl;
 
  dump_gds_cell(f, it_root, all_patterns);
 
  f << "ENDLIB" << std::endl;
}
 
#endif // DUMP_GDS
 
//////////////////////////////////////////////////////////////////////////////////////////
 
void read_input(const char *const args[], Patterns &initial_patterns, Context &context)
{ // Relies on the standard convention: `args[]` is terminated by a null pointer 
  std::stringstream params;
 
  {
    struct Arg
    {
      const char *arg;
      unsigned i_arg;
    };
 
    auto pre_arg = [=](Arg &arg) -> bool
    {
      if (arg.arg == nullptr)
        return false;
 
      if (*arg.arg != '\0')
        return true;
 
      arg.arg = args[++arg.i_arg];
      return arg.arg != nullptr;
    };
 
    auto consume = [&](Arg &arg, const char *str) -> bool
    {
      if (!pre_arg(arg))
        return false;
 
      std::size_t n = std::strlen(str);
      return std::strncmp(arg.arg, str, n) == 0 ? arg.arg += n, true : false;
    };
 
    auto consume_uint = [&](Arg &arg) -> unsigned
    {
      consume(arg, "=");
 
      if (!pre_arg(arg))
        throw std::invalid_argument("missing argument");
 
      std::size_t n;
      unsigned long v = std::stoul(arg.arg, &n);
      arg.arg += n;
 
      if (v > std::numeric_limits<unsigned>::max())
        throw std::out_of_range("argument out of range");
 
      return v;
    };
 
    Arg arg = { args[0] };
    while (pre_arg(arg))
    {
      if (consume(arg, "-"))
      {
        consume(arg, "-");
        if (consume(arg, "waste_abs"))
        { // Percentage of the full area
          context.allowed_waste_perc = consume_uint(arg);
          if (context.allowed_waste_perc > 100)
            throw std::out_of_range("argument out of range");
 
          context.is_absolute_waste = true;
        } 
        else if (consume(arg, "waste_rel"))
        { // Percentage of the partial solution area
          context.allowed_waste_perc = consume_uint(arg);
          if (context.allowed_waste_perc > 100)
            throw std::out_of_range("argument out of range");
 
          context.is_absolute_waste = false;
        } 
        else if (consume(arg, "waste"))
        { // Exact area
          context.allowed_waste_perc = -1;
          context.allowed_waste = consume_uint(arg);
          context.is_absolute_waste = true;
        }
        else if (consume(arg, "threads"))
          context.n_threads = consume_uint(arg);
      }
      else
      {
        params << ' ' << arg.arg;
        arg.arg += std::strlen(arg.arg);
      }
    }
  }
 
  {
    std::istream &in = params.tellp() == 0 ? std::cin : params;
 
    in >> context.limits;
 
    unsigned n_blocks = 0;
    if (!(in >> n_blocks))
      throw std::invalid_argument("invalid number of blocks");
 
    for (unsigned i = 0; i < n_blocks; ++i)
    {
      Rect box;
      in >> box;
 
      {
        PatternDesc &desc = initial_patterns[box];
        if (desc.waste != 0)
        { // New entry
          desc = { 0 };
  #ifdef DUMP_GDS
          desc.id = i + 1;
          desc.composition = Composition::ORIGINAL;
  #endif // DUMP_GDS
 
          context.originals.push_back(box);
        }
      }
      
      box.flip();
 
      {
        PatternDesc &desc = initial_patterns[box];
        if (desc.waste != 0)
        { // New entry
          desc = { 0 };
  #ifdef DUMP_GDS
          desc.id = i + 1;
          desc.composition = Composition::ORIGINAL;
  #endif // DUMP_GDS
 
          context.originals.push_back(box);
        }
      }
    }
  }
}
 
void display_input(const Context &context)
{
  std::cout << "Limits: " << context.limits << std::endl;
 
  std::cout << "Blocks:";
 
  unsigned n_blocks = 0;
  for (const Rect &box : context.originals)
    if (!box.is_horizontal())
    {
      std::cout << ' ' << box;
      ++n_blocks;
    }
 
  std::cout << " (" << n_blocks << ")" << std::endl;
 
  std::cout << "Allowable intermediate waste: ";
  if (context.allowed_waste_perc != -1)
  {
    assert(context.allowed_waste_perc <= 100);
    std::cout << context.allowed_waste_perc << "% " <<
      (context.allowed_waste_perc == 100 ? "(unlimited)" :
       context.allowed_waste_perc == 0 ? "(perfect)" :
       context.is_absolute_waste ? "(absolute)" : "(relative)");
  }
  else
    std::cout << context.allowed_waste << " sq units " <<
      (context.allowed_waste >= context.limits.area() ? "(unlimited)" :
       context.allowed_waste == 0 ? "(perfect)" : "");
 
  std::cout << std::endl;
 
  std::cout << "Threads: " << context.n_threads << std::endl;
}
 
//////////////////////////////////////////////////////////////////////////////////////////
 
int main(int argc, char *argv[])
{
  try
  {
    Context context = {};
 
    Patterns all_patterns;
    std::vector<Patterns> new_patterns(context.n_threads);
 
    read_input(argv + 1, new_patterns[0], context);
    display_input(context);
 
    context.postprocess();
 
    std::cout << "Working..." << std::endl;
 
    auto timing_start = std::chrono::high_resolution_clock::now();
 
    std::sort(context.originals.begin(), context.originals.end(), 
      [](const Rect &lhs, const Rect &rhs) { return lhs.area() < rhs.area(); });
    context.min_original_area = context.originals.front().area();
    assert(context.min_original_area > 0);
 
    // Start processing
 
    std::vector<ThreadContext> threads(context.n_threads);
 
    ItsUpdated its_updated;
    // Declared outside the cycle to maintain capacity
 
    do
    {
      assert(its_updated.empty());
 
      // All patterns in all 'new_patterns[]' are either completely new or better than 
      // matching existing patterns in 'all_patterns'. However, it is possible that multiple 
      // threads, working independently, generated same-sized patterns or improved on same 
      // pattern in 'all_patterns'. We have to keep only the best one. To make sure we don't 
      // include improvements for the same pattern into 'its_updated' multiple times, let's 
      // first merge all 'new_patterns[]' to 'new_patterns[0]' and only then transfer the 
      // results to 'all_patterns'
 
      // Merge new patterns and improvements to 'new_patterns[0]'
 
      for (unsigned n_merge_step = 1; n_merge_step < context.n_threads; n_merge_step *= 2)
      {
        unsigned n_threads = 0;
 
        for (unsigned i_patterns = 0; i_patterns + n_merge_step < context.n_threads;
               i_patterns += n_merge_step * 2)
        {
          ThreadContext &thread = threads[n_threads++];
          thread.thread = std::thread(merge_new_patterns, 
            std::ref(new_patterns[i_patterns]), 
            std::ref(new_patterns[i_patterns + n_merge_step]), nullptr);
        }
 
        for (ThreadContext &thread : std::span<ThreadContext>(threads.begin(), n_threads))
          thread.thread.join();
      }
 
      // Transfer new patterns and improvements to 'all_patterns'
 
      its_updated.reserve(new_patterns[0].size());
      merge_new_patterns(all_patterns, new_patterns[0], &its_updated);
 
#ifndef NDEBUG
      for (const Patterns& patterns : new_patterns)
        assert(patterns.empty());
#endif // NDEBUG
 
      if (its_updated.empty())
        break;
 
      // Generate new patterns
 
      std::size_t i_begin = 0, i_end;
      for (unsigned i_thread = 0; i_thread < context.n_threads; ++i_thread, i_begin = i_end)
      {
        i_end = its_updated.size() * (i_thread + 1) / context.n_threads;
        ThreadContext &thread = threads[i_thread];
        EXTRA_STATS_ONLY(thread.extra_stats = {});
        thread.thread = std::thread(generate_new_patterns, 
          ItsUpdatedSpan(its_updated.begin() + i_begin, its_updated.begin() + i_end),
          std::cref(all_patterns), std::ref(new_patterns[i_thread]), 
          std::cref(context), std::ref(thread));
      }
 
      for (ThreadContext &thread : threads)
      {
        thread.thread.join();
        EXTRA_STATS_ONLY(context.extra_stats += thread.extra_stats);
      }
 
      // Release the update list
 
      for (Patterns::const_iterator it : its_updated)
      {
        assert(it->second.index > 0);
        it->second.index = 0;
      }
 
      its_updated.clear();
 
    } while (true);
 
    // Find the best pattern
 
    Patterns::const_iterator it_min = all_patterns.begin();
    Area min_total_waste = context.total_waste(*it_min);
 
    for (Patterns::const_iterator it = all_patterns.begin(); it != all_patterns.end(); ++it)
    {
      Area total_waste = context.total_waste(*it);
      if (total_waste < min_total_waste)
      {
        min_total_waste = total_waste;
        it_min = it;
      }
    }
 
    // Done
 
    auto timing_end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> timing = timing_end - timing_start;
 
#ifdef EXTRA_STATS
    std::cout << "Compositions: " << context.extra_stats.n_compositions << std::endl;
    std::cout << "Patterns built: " << context.extra_stats.n_patterns_built << std::endl;
    std::cout << "Pattern updates: " << context.extra_stats.n_patterns_updated << std::endl;
#endif // EXTRA_STATS
 
    std::cout << "Patterns: " << all_patterns.size() << std::endl;
    std::cout << "Min waste: " << min_total_waste << std::endl;
    std::cout << "Duration: " << std::fixed << std::setprecision(2) << timing.count() << "s" << std::endl;
 
#ifdef DUMP_GDS
    std::cout << "Saving GDS file..." << std::endl;
    dump_gds("result.gds", it_min, all_patterns, context);
    std::cout << "Done." << std::endl;
#endif // DUMP_GDS
  }
  catch (const std::exception &e)
  {
    std::cerr << "Error: " << e.what() << std::endl;
    return EXIT_FAILURE;
  }
  catch (...)
  {
    return EXIT_FAILURE;
  }
}
В приведенном коде задача пока по-прежнему решается неограниченная. Надо бы добавить ограничения на количество заготовок.

Теортетические статьи по теме действительно пишут, что неограниченная задача допускает эффективное решение через динамическое программирование, то есть в качестве решения неограниченной задачи вышеприведенный код не имеет большого смысла. Это скорее заготовка для решения ограниченной задачи.

Еще почитываю...
0
0 / 0 / 0
Регистрация: 19.06.2018
Сообщений: 1
08.08.2022, 13:55
Добрый день, уважаемые коллеги! А есть ли такое решение для ограниченного количества заготовок?... Так сказать самый обычный раскрой листового материала ЛДСП...
Имеется некий Форматно-Раскроечный центр, и карты раскроя в него забиваются вручную с распечатанных карт раскроя базис, и вот хотелось бы просто указывать формат листа, забивать размеры и количество заготовок, а программа создавала карту раскроя. ПО управления станком написано на C# и имеется возможность его адаптации для принятия некой карты раскроя сформированной в какой-то программе. Вот собственно такую программу и планируется реализовать... Не могу начать ее писать, не хватает волшебного пендаля или внятного объяснения порядка действий )) Перечитал кучу литературы про гильотинный раскрой, упаковку прямоугольников, рюкзак... Но в голове какая-то каша))

Буду благодарен за любую помощь
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
08.08.2022, 13:55

Вероятность случайно выбраной детали без дефектов
Помогите пожалуйста с решение задачи. Детали попадают на предприятие с 3-их цехов: 50% - с 1-го, 30% - с 2-го и 20% с 3 - го. При этом...

Посоветуйте литературу по выполнению прямоугольной изометрии детали, эскиза детали
посоветуйте литературу по выполнению прямоугольной изометрии детали,эскиза детали

Сделать линию без прямоугольника вокруг
Доброго времени суток! Есть карта на SVG, я хочу её переделать в обычную графику, чтобы не грузить сайт кодом, да и SVG не везде...

Разрезы
Помогите пожалуйста сделать необходимые разрезы.

Найти минимальную площадь прямоугольника из данного набора (без массива)
дано целое число N и набор из N прямоугольников, заданных своими сторонами - парами чисел(а,б).Найти минимальную площадь прямоугольника из...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
25
Ответ Создать тему
Новые блоги и статьи
Скрипты Tampermonkey для CyberForum, ChatGPT, Claude и пр.
Jin X 06.09.2026
Скрипты Tampermonkey для CyberForum, ChatGPT, Claude и пр. Работая с форумом и нейросетями в браузере часто хочется что-то подкорректировать или добавить какого-то функционала. Ниже прикреплён. . .
Программа опроса у.з. расходомера SLS-720F
Argus19 02.09.2026
Программа опроса у. з. расходомера SLS-720F Программа опрашивает один раз в минуту три ультразвуковых расходомера SLS-720F через интерфейс RS-485 по протоколу Modbus RTU. Опрашиваются регистры. . .
Hyper-V: Компьютер должен поддерживать доверенный платформенный модуль 2.0.
Maks 31.08.2026
При установке Windows 11 на виртуальную машину Hyper-V 2-го поколения вылезла такая ошибка: Решение: в параметрах виртуальной машины, в разделе "Безопасность" (Security) активировать флаг. . .
Архитектура биовида Стива в Майнкрафте: Зачем бонобо кубический каннибализм
anaschu 30.08.2026
Кубический Вагинокапитализм в Minecraft: Математический инвариант ОДУ и рок Стивов-бонобо Главная задача разработанной «Модели Всего» — наглядно продемонстрировать наличие системной «судьбы». . .
Оттачиваю умение писать js программы.
russiannick 30.08.2026
Проектом выходного дня стало написание Книги шифров Виженера. Итогом стала версия 200, синий туман. Синий туман назван так, потому что замораживает текст под собой. Нажатие синих кнопок управляют. . .
мат медиц модель 30. презентация проекта
anaschu 27.08.2026
хоп хоп хоп хидахоп, а я кладую))
Как у меня протекала болезнь
zorxor 27.08.2026
Здравствуйте, друзья! Эта запись блога предназначена именно для вас - для моих дорогих друзей, которые знали меня лично. Чтобы ответить на вопрос - а что же со мной произошло на самом деле? Я учился. . .
Нашел вот забавное видео о измерениях. Лучшее что я видел на эту тему
kumehtar 26.08.2026
ILETXiw9bMQ Основная суть и тезисы по измерениям: 0D (Нулевое измерение): точка, не имеющая длины, ширины, высоты или объема. Объект не может перемещаться в 0D. 1D (Первое измерение):. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru