0 / 0 / 0
Регистрация: 02.06.2014
Сообщений: 4
1

Шахматы. Каждый ферзь бьет ровного одного ферзя

02.06.2014, 09:01. Показов 3075. Ответов 6
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Всем привет! Помогите решить задачу: Расставить на шахматной доске максимальное число ферзей так, чтобы каждый нападал ровно на одного ферзя.
Вот что получилось:
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
/*
Описание:
Промежуточные данные:
    1. int x[8] - координаты расположения ферзей. Номер вертикали определяется
        индексом элемента массива, номер горизонтали - его значением;
        Например, выражение x[3] = 5 означает, что на пересечении 4-й вертикали и
        6-й горизонтали расположен ферзь (массивы в C++ индексируются с нуля!).
    2. bool a[8] - массив признаков безопасности горизонталей шахматной доски
        (true - горизонталь безопасна, false - горизонталь находится под ударом
        одного или нескольких ферзей);
    3. bool b[15] - массив признаков безопасности диагоналей "справа сверху влево
        вниз" шахматной доски(true - диагональ безопасна, false - диагональ
        находится под ударом). Номер такой диагонали равен сумме координат занятой
        ферзём клетки;
    4. bool c[15] - массив признаков безопасности диагоналей "слева снизу вправо
        вверх" шахматной доски(true - диагональ безопасна, false - диагональ
        находится под ударом). Номер такой диагонали равен разности координат
        занятой ферзём клетки плюс 7
    5. int st_sol_numb - начальный номер решения для вывода на экран.*/
#include <stdio.h>
#include <clocale>
#include <conio.h>
#define _CRT_SECURE_NO_DEPRECATE 0
#define _CRT_SECURE_NO_WARNINGS 0
int  x[8];
bool l[8],a[8], b[15], c[15];
 
//функция печати расположения ферзей на доске
void PrintChessBoard();
//функция установки ферзя
void TryInstallQueen(int i);
 
int main(){
    setlocale(LC_ALL, "Russian");
    for (int i = 0; i < 8; i++){
        a[i] = true;
        l[i] = true;
    }
    for (int i = 0; i < 15; i++){
        b[i] = true;
        c[i] = true;
    }
 
    TryInstallQueen(0);
 
    return 0;
}
 
/*ФУНКЦИЯ ПЕЧАТИ РАСПОЛОЖЕНИЯ ФЕРЗЕЙ НА ШАХМАТНОЙ ДОСКЕ
Входные данные: отсутствуют.
Возвращаемое значение: отсутствует
Локальные переменные:
    1. int i - счётчик горизонталей;
    2. int j - счётчик вертикалей;
    3. static int solution_numb - счётчик числа напечатанных решений. 
        Статическая переменная, сохраняющая своё значение после выхода из функции;*/
void PrintChessBoard(){
    static int solution_numb = 1;
 
    printf("\n РЕШЕНИЕ №%d\n", solution_numb++);
    for (int i = 0; i < 8; i++){
        if (i == 0)
            printf("   A B C D E F G H ");
        printf("\n  -----------------\n%d |", i + 1);
 
        for (int j = 0; j < 8; j++)
            if (i == x[j])
                printf("Q|");
            else
                printf(" |");
 
        if (i == 7)
            printf("\n  -----------------\n\n");
    }//for i
    return;
}
 
 
/*ФУНКЦИЯ УСТАНОВКИ ФЕРЗЯ
Входные данные: 
1. int i номер вертикали, в которую необходимо установить ферзя
Возвращаемое значение: отсутствует
Локальные переменные:*/
void TryInstallQueen(int i)
{   {int m=i+1;
        l[i] = true;
    for (int j1 = 0; (j1 < 8); j1++){
    for (int j2 = 2; (j2 < 8); j2++){
        if ((a[j1] && b[i + j1] && c[i - j1 + 7]) & (a[j2] && b[i + j2] && c[i - j2 + 7])){
            x[i] = j1;
            a[j1] = false;
            b[i+ j1] = false;
            c[i - j1 + 7] = false;
            x[i] = j2;
            b[i+ j2] = false;
            c[i - j2 + 7] = false;
            l[i] = false;
 
 
            if (i < 7)
                TryInstallQueen(i+1);
            else
                PrintChessBoard();
 
            a[j1] = true;
            b[i + j1] = true;
            c[i - j1 + 7] = true;
            b[i + j2] = true;
            c[i - j2 + 7] = true;
            /*if  (((a[j1] && b[i + j1] && c[i - j1 + 7]) == (a[j1] && b[m + j1] && c[m - j1 + 7])) || 
            ((a[j1] && b[i + j1] && c[i - j1 + 7]) == (a[j1] && b[m + j1] && c[m - j1 + 7]))) {
 
                l[i] = false;
            }*/
        }//if (a[j] && b[i + j] && c[i - j + 7]){
    }//for j
} 
 
}
    return;
    getch();
}
у меня выводит только несколько вариантов, причем они не совсем правильные(
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
02.06.2014, 09:01
Ответы с готовыми решениями:

Шахматы: определить, бьёт ли ферзь коня, конь ферзя или фигуры не угрожают друг другу
Доброго времени суток. Помогите с задачей. Надо написать программу, которая будет определять бьёт...

Определить, бьет ферзь коня, конь — Ферзя, или фигуры не угрожают друг другу
Координаты двух полей шахматной доски заданы в виде двух пар чисел x1 , у1 и х2 , у2. На первом...

Отметить положение ферзя и клетки, которые он бьет
На шахматной доске стоит ферзь. Отметьте положение ферзя на доске и все клетки, которые бьет ферзь....

Выяснить бьёт ли ферзь коня
На шахматной доске стоят конь и ферзь. На вход подаются координаты ферзя и коня и число n (n=1...

6
интересующийся
311 / 282 / 93
Регистрация: 25.09.2010
Сообщений: 1,056
02.06.2014, 12:48 2

Не по теме:

Можно посмотреть в сторону backtracking:
http://en.wikibooks.org/wiki/A... cktracking
http://en.wikipedia.org/wiki/Backtracking


Сразу не заметил, что ты уже попытался воплотить сей алгоритм
0
0 / 0 / 0
Регистрация: 02.06.2014
Сообщений: 4
02.06.2014, 13:59  [ТС] 3
а примерный код можно? а то теоретически я это понимаю, а реализовать как то пока не очень получается
0
интересующийся
311 / 282 / 93
Регистрация: 25.09.2010
Сообщений: 1,056
02.06.2014, 16:22 4
после работы попробую решить)
0
Эксперт С++
3224 / 1751 / 436
Регистрация: 03.05.2010
Сообщений: 3,867
03.06.2014, 20:30 5
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
/////////////////////////////////////////////////////////////////////////////////////////
//Расставить на шахматной доске максимальное число ферзей так, чтобы каждый нападал 
//ровно на одного ферзя.
/////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <complex>
#include <conio.h>
#include <functional>
#include <iostream>
#include <vector>
/////////////////////////////////////////////////////////////////////////////////////////
int     const   BOARD_SIZE  =   8;
int     const   MAX_COORD   =   BOARD_SIZE - 1;
/////////////////////////////////////////////////////////////////////////////////////////
class  T_queen
{
    int     x_;
    int     y_;
    int     attack_counter_;
    //-----------------------------------------------------------------------------------
public:
    //-----------------------------------------------------------------------------------
    T_queen
        (
            int     x   =   0,
            int     y   =   0
        )
        :
        x_                  ( x ),
        y_                  ( y ),
        attack_counter_     ()
    {}
    //-----------------------------------------------------------------------------------
    void  print()                               const
    {
        std::cout   <<  std::complex<int>
                            (
                                x_ + 1,
                                y_ + 1
                            );
    }
    //-----------------------------------------------------------------------------------
    void  clear_attack_counter()
    {
        attack_counter_  =   0;
    }
    //-----------------------------------------------------------------------------------
    T_queen  get_queen_with_next_pos()          const
    {
        T_queen     queen( *this );
        queen.inc_pos();
        return  queen;
    }
    //-----------------------------------------------------------------------------------
    bool  is_max_pos()                          const
    {
        return      x_  ==  MAX_COORD
                &&  y_  ==  MAX_COORD;
    }
    //-----------------------------------------------------------------------------------
    void  inc_pos()
    {
        if( x_ < MAX_COORD )
        {
            ++x_;
        }
        else if( y_ < MAX_COORD )
        {
            x_  =   0;
            ++y_;
        }
    }
    //-----------------------------------------------------------------------------------
    void  check_attack( T_queen  &   queen )
    {
        int     X_abs_dist  =   abs( x_ - queen.x_ );
        int     Y_abs_dist  =   abs( y_ - queen.y_ );
 
        bool    is_attack   =           ( X_abs_dist - Y_abs_dist ) 
                                    *   X_abs_dist 
                                    *   Y_abs_dist
                                ==  0;
 
        if( is_attack )
        {
            inc_attack_counter          ();
            queen.inc_attack_counter    ();
        }
    }
    //-----------------------------------------------------------------------------------
    void  inc_attack_counter()
    {
        ++attack_counter_;
    }
    //-----------------------------------------------------------------------------------
    operator int()          const
    {
        return  attack_counter_;
    }
    //-----------------------------------------------------------------------------------
};
/////////////////////////////////////////////////////////////////////////////////////////
typedef std::vector< T_queen    >  T_position;
typedef std::vector< T_position >  T_positions;
/////////////////////////////////////////////////////////////////////////////////////////
void  clear_all_attack_counters( T_position   &   position )
{
    std::for_each
        (
            position.begin(),
            position.end(),
            std::mem_fun_ref( &T_queen::clear_attack_counter )
        );
}
/////////////////////////////////////////////////////////////////////////////////////////
void  count_attacks( T_position   &   position )
{
    for( size_t  i = 0; i < position.size(); ++i )
    {
        for( size_t  j = i + 1; j < position.size(); ++j )
        {
            position[i].check_attack( position[j] );
        }//for
    }//for
}
/////////////////////////////////////////////////////////////////////////////////////////
int  max_attack_counter( T_position  const   &   position )
{
    return  *std::max_element
                (
                    position.begin  (),
                    position.end    ()
                );
}
/////////////////////////////////////////////////////////////////////////////////////////
bool  position_is_bad( T_position   &   position )
{
    clear_all_attack_counters    ( position );
    count_attacks                ( position );
    return  max_attack_counter   ( position )    >   1;
}
/////////////////////////////////////////////////////////////////////////////////////////
int  min_attack_counter( T_position  const   &   position )
{
    return  *std::min_element
                (
                    position.begin  (),
                    position.end    ()
                );
}
/////////////////////////////////////////////////////////////////////////////////////////
bool  position_is_good( T_position  &   position )
{
    clear_all_attack_counters    ( position );
    count_attacks                ( position );
 
    return      min_attack_counter( position )  ==  1
            &&  max_attack_counter( position )  ==  1;
}
/////////////////////////////////////////////////////////////////////////////////////////
void  go_to_next_not_bad_position( T_position  &   position )
{
    if  (
            position.back().is_max_pos()
        )
    {
        position.pop_back();
 
        if  (
                position.empty()
            )
        {
            return;
        }
        else
        {
            position.back().inc_pos();
        }//else
    }
    else
    {
        position.push_back
            (
                position.back().get_queen_with_next_pos()
            );
    }
 
    while   (
                position_is_bad( position )
            )
    {
        if  (
                position.back().is_max_pos()
            )
        {
            go_to_next_not_bad_position( position );
        }
        else
        {
            position.back().inc_pos();
        }
    }//while
}
/////////////////////////////////////////////////////////////////////////////////////////
void  print_queens_position( T_position  const   &   position )
{
    std::for_each
        (
            position.begin      (),
            position.end        (),
            std::mem_fun_ref    ( &T_queen::print )
        );
}
/////////////////////////////////////////////////////////////////////////////////////////
void  find_and_print_good_positions( T_position   &   good_position_with_max_size )
{
    size_t      max_good_position_size   =   0;
 
 
    T_position  position
                    (
                        1,
                        T_queen()
                    );
 
 
    while   (
                !position.empty()
            )
    {
        if  (
                    position_is_good    ( position )
                &&      position.size   ()
                    >=  max_good_position_size
            )
        {
            good_position_with_max_size     =   position;
            max_good_position_size          =   position.size();
            print_queens_position( position );
            std::cout   <<  std::endl;
        }//if
 
        go_to_next_not_bad_position( position );
    }//whle
}
/////////////////////////////////////////////////////////////////////////////////////////
int  main()
{
    std::locale::global(std::locale(""));
    T_position  position;
    find_and_print_good_positions( position );
}
0
0 / 0 / 0
Регистрация: 02.06.2014
Сообщений: 4
03.06.2014, 23:25  [ТС] 6
Большое спасибо!!!
0
Эксперт С++
3224 / 1751 / 436
Регистрация: 03.05.2010
Сообщений: 3,867
06.06.2014, 10:55 7
Вычислил позиции из десяти ферзей без поворотов и отражений, и был удивлен, что их почти сотня, в то время как позиций ферзей, не бьющих друг друга, на порядок меньше.
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
/////////////////////////////////////////////////////////////////////////////////////////
//Расставить на шахматной доске максимальное число ферзей так, чтобы каждый нападал 
//ровно на одного ферзя.
/////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <complex>
#include <conio.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <limits>
#include <set>
#include <utility>
#include <vector>
/////////////////////////////////////////////////////////////////////////////////////////
int     const   BOARD_SIZE  =   8;
int     const   MAX_COORD   =   BOARD_SIZE - 1;
/////////////////////////////////////////////////////////////////////////////////////////
class  T_queen
{
    int     x_;
    int     y_;
    int     attack_counter_;
    //-----------------------------------------------------------------------------------
public:
    //-----------------------------------------------------------------------------------
    T_queen
        ()
        :
        x_                  (),
        y_                  (),
        attack_counter_     ()
    {}
    //-----------------------------------------------------------------------------------
    int  get_attack_counter()                   const
    {
        return  attack_counter_;
    }
    //-----------------------------------------------------------------------------------
    void  print()                               const
    {
        std::cout   <<  std::complex<int>
                            (
                                x_ + 1,
                                y_ + 1
                            );
    }
    //-----------------------------------------------------------------------------------
    void  clear_attack_counter()
    {
        attack_counter_ = 0;
    }
    //-----------------------------------------------------------------------------------
    T_queen  get_queen_with_next_pos()          const
    {
        T_queen     queen( *this );
        queen.inc_pos();
        return  queen;
    }
    //-----------------------------------------------------------------------------------
    bool  is_max_pos()                          const
    {
        return      x_  ==  MAX_COORD
                &&  y_  ==  MAX_COORD;
    }
    //-----------------------------------------------------------------------------------
    void  inc_pos()
    {
        if( x_ < MAX_COORD )
        {
            ++x_;
        }
        else if( y_ < MAX_COORD )
        {
            x_ = 0;
            ++y_;
        }
    }
    //-----------------------------------------------------------------------------------
    void  count_attack( T_queen  &   queen )
    {
        int     X_abs_dist  =   abs( x_ - queen.x_ );
        int     Y_abs_dist  =   abs( y_ - queen.y_ );
 
        bool    is_attack   =           ( X_abs_dist - Y_abs_dist ) 
                                    *   X_abs_dist 
                                    *   Y_abs_dist
                                ==  0;
 
        if( is_attack )
        {
            ++attack_counter_;
            ++queen.attack_counter_;
        }//if
    }
    //-----------------------------------------------------------------------------------
    bool  operator< ( T_queen   const   &   queen )     const
    {
        return      std::make_pair
                        (
                            x_,
                            y_
                        )
 
                <   std::make_pair
                        (
                            queen.x_,
                            queen.y_
                        );
    }
    //-----------------------------------------------------------------------------------
    void  rotate()
    {
        reflect     ();
        transpose   ();
    }
    //-----------------------------------------------------------------------------------
    void  reflect()
    {
        x_  =   MAX_COORD - x_;
    }
    //-----------------------------------------------------------------------------------
private:
    //-----------------------------------------------------------------------------------
    void  transpose()
    {
        std::swap( x_, y_ );
    }
    //-----------------------------------------------------------------------------------
};
/////////////////////////////////////////////////////////////////////////////////////////
typedef std::vector < T_queen   >   T_queens;
typedef std::vector < int       >   T_attack_counters;
/////////////////////////////////////////////////////////////////////////////////////////
class  T_position
{
    //-----------------------------------------------------------------------------------
    T_queens            queens_;
    int                 min_attack_counter_;
    int                 max_attack_counter_;
    T_attack_counters   attack_counters_;
    //-----------------------------------------------------------------------------------
public:
    //-----------------------------------------------------------------------------------
    typedef std::set    < T_position    >   T_positions;
    //-----------------------------------------------------------------------------------
    T_position()
        :
        queens_
            (
                1,
                T_queen()
            )
    {
        clear_all_attack_counters();
    }
    //-----------------------------------------------------------------------------------
    bool  empty()                                           const
    {
        return  queens_.empty();
    }
    //-----------------------------------------------------------------------------------
    bool  is_good()
    {
        count_attack_counters();
 
        return      min_attack_counter_     ==  1
                &&  max_attack_counter_     ==  1;
    }
    //-----------------------------------------------------------------------------------
    bool  is_bad()
    {
        count_attack_counters();
 
        return  max_attack_counter_ > 1;
    }
    //-----------------------------------------------------------------------------------
    size_t  size()                                          const
    {
        return  queens_.size();
    }
    //-----------------------------------------------------------------------------------
    bool  operator< ( T_position    const   &   position )  const
    {
        return  queens_ < position.queens_;
    }
    //-----------------------------------------------------------------------------------
    T_position  get_min_position_inv_for_move()             const
    {
        T_positions     positions_inv_for_move;
        T_position      cur_position(*this);
 
        insert_all_rotated_positions_of_into
            (
                cur_position,
                positions_inv_for_move
            );
 
        reflect_and_sort_position( cur_position );
 
        insert_all_rotated_positions_of_into
            (
                cur_position,
                positions_inv_for_move
            );
 
        return  *positions_inv_for_move.begin();
    }
    //-----------------------------------------------------------------------------------
    void  print()                                           const
    {
        std::for_each
            (
                queens_.begin       (),
                queens_.end         (),
                std::mem_fun_ref    ( &T_queen::print )
            );
    }
    //-----------------------------------------------------------------------------------
    void  go_to_next_not_bad_position()
    {
        if  (
                queens_.back().is_max_pos()
            )
        {
            queens_.pop_back();
 
            if  (
                    queens_.empty()
                )
            {
                return;
            }
            else
            {
                queens_.back().inc_pos();
            }//else
        }
        else
        {
            queens_.push_back
                (
                    queens_.back().get_queen_with_next_pos()
                );
        }
 
        while   (
                    is_bad()
                )
        {
            if  (
                    queens_.back().is_max_pos()
                )
            {
                go_to_next_not_bad_position();
            }
            else
            {
                queens_.back().inc_pos();
            }
        }//while
    }
    //-----------------------------------------------------------------------------------
private:
    //-----------------------------------------------------------------------------------
    static void  insert_all_rotated_positions_of_into
        (
            T_position      &   position,
            T_positions     &   positions
        )
    {
        positions.insert            ( position );
 
        rotate_and_sort_position    ( position );
        positions.insert            ( position );
 
        rotate_and_sort_position    ( position );
        positions.insert            ( position );
 
        rotate_and_sort_position    ( position );
        positions.insert            ( position );
    }
    //-----------------------------------------------------------------------------------
    static void  rotate_and_sort_position( T_position   &   position )
    {
        std::for_each
            (
                position.queens_.begin  (),
                position.queens_.end    (),
                std::mem_fun_ref        ( &T_queen::rotate )
            );
 
        std::sort
            (
                position.queens_.begin  (),
                position.queens_.end    ()
            );
    }
    //-----------------------------------------------------------------------------------
    static void  reflect_and_sort_position( T_position  &   position )
    {
        std::for_each
            (
                position.queens_.begin  (),
                position.queens_.end    (),
                std::mem_fun_ref        ( &T_queen::reflect )
            );
 
        std::sort
            (
                position.queens_.begin  (),
                position.queens_.end    ()
            );
    }
    //-----------------------------------------------------------------------------------
    void  count_attack_counters()
    {
        clear_all_attack_counters           ();
        count_attacks                       ();
        count_min_and_max_attack_counters   ();
    }
    //-----------------------------------------------------------------------------------
    void  clear_all_attack_counters()
    {
        std::for_each
            (
                queens_.begin       (),
                queens_.end         (),
                std::mem_fun_ref    ( &T_queen::clear_attack_counter )
            );
 
        min_attack_counter_ = 0;
        max_attack_counter_ = 0;
        attack_counters_.clear();
    }
    //-----------------------------------------------------------------------------------
    void  count_attacks()
    {
        for( size_t  i = 0; i < queens_.size(); ++i )
        {
            for( size_t  j = i + 1; j < queens_.size(); ++j )
            {
                queens_[i].count_attack( queens_[j] );
            }//for
        }//for
    }
    //-----------------------------------------------------------------------------------
    void  count_min_and_max_attack_counters()
    {
        std::transform
            (
                queens_.begin       (),
                queens_.end         (),
                std::back_inserter  ( attack_counters_ ),
                std::mem_fun_ref    ( &T_queen::get_attack_counter )
            );
        
        min_attack_counter_     =   *std::min_element
                                        (
                                            attack_counters_.begin  (),
                                            attack_counters_.end    ()
                                        );
 
        max_attack_counter_     =   *std::max_element
                                        (
                                            attack_counters_.begin  (),
                                            attack_counters_.end    ()
                                        );
    }
    //-----------------------------------------------------------------------------------
};
/////////////////////////////////////////////////////////////////////////////////////////
void  find_good_positions_inv_for_move( T_position::T_positions   &   positions )
{
    size_t  max_position_size   =   0;
 
    T_position  position;
 
    while   (
                !position.empty()
            )
    {
        if  (
                    position.is_good    ()
                &&  position.size       ()  >=  max_position_size
            )
        {
            if  (
                    position.size() > max_position_size
                )
            {
                max_position_size   =   position.size();
            }
            positions.insert
                (
                    position.get_min_position_inv_for_move()
                );
 
            position.print();
            std::cout   <<  std::endl;
        }
        position.go_to_next_not_bad_position();
    }//whle
}
/////////////////////////////////////////////////////////////////////////////////////////
struct  T_print_ind_size_and_position
{
    //-----------------------------------------------------------------------------------
    int     position_counter_;
    size_t  prev_size_;
    //-----------------------------------------------------------------------------------
    T_print_ind_size_and_position()
        :
        position_counter_   (),
        prev_size_          ()
    {}
    //-----------------------------------------------------------------------------------
    void  operator() ( T_position   const   &   position )
    {
        if( position.size() != prev_size_ )
        {
            position_counter_   =   0;
            prev_size_          =   position.size();
            std::cout   <<  std::endl;
        }
 
        std::cout   <<  "#"
                    <<  ++position_counter_
                    <<  '\t'
                    <<  "size = "
                    <<  prev_size_
                    <<  '\t';
 
        position.print();
        std::cout   <<  std::endl;
    }
    //-----------------------------------------------------------------------------------
};
/////////////////////////////////////////////////////////////////////////////////////////
void  print_positions( T_position::T_positions  const   &   positions )
{
    std::for_each
        (
            positions.begin                 (),
            positions.end                   (),
            T_print_ind_size_and_position   ()
        );
}
/////////////////////////////////////////////////////////////////////////////////////////
int  main()
{
    std::locale::global(std::locale(""));
 
    T_position::T_positions     positions_inv_for_move;
    find_good_positions_inv_for_move( positions_inv_for_move );
 
    std::cout   <<  std::endl
                <<  "Позиции ферзей, каждый из которых атакует только одного "
                <<  std::endl
                <<  "(без поворотов и отражений):"
                <<  std::endl;
 
    print_positions( positions_inv_for_move );
    std::cout   <<  "finish"
                <<  std::endl;
 
    system("pause");
}
0
06.06.2014, 10:55
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
06.06.2014, 10:55
Помогаю со студенческими работами здесь

Определить, бьет ли Ферзь Короля
1.Требуется определить, бьет ли ферзь, стоящий на клетке с указанными координатами (номер строки и...

Определить, бьет ли ферзь произвольную фигуру
Положение шахматных фигур на доске задается: - по горизонтали буквами; - по вертикали цифрами; ...

Проверить, бьет ли ферзь другую фигуру
Требуется определить, бьет ли ферзь, стоящий на клетке с указанными координатами (номер строки и...

Алгоритм на Javascript - два ферзя на доске и бьет ли один другого
Такой алгоритм есть function check(first_queen, second_queen) { var fx = first_queen; ...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru