Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.59/29: Рейтинг темы: голосов - 29, средняя оценка - 4.59
1 / 1 / 3
Регистрация: 02.02.2012
Сообщений: 73

Проверка графа, заданного матрицей смежности, на двудольность

24.02.2013, 12:29. Показов 6238. Ответов 5
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте!!! Подскажите пожалуйста алгоритм, с помощью которого можно проверить граф, заданный матрицей смежности, на двудольность. Спасибо!!!
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
24.02.2013, 12:29
Ответы с готовыми решениями:

Двудольные графы. Проверка графа на двудольность
Граф называется двудольным, если его вершины можно раскрасить в два цвета так, что нет ребер, соединяющих вершины одинакового цвета (то...

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

Реализация алгоритма Краскала для графа, который задается матрицей смежности
Доброго времени! Начала изучать Python и очень срочно необходимо реализовать алгоритм Краскала для графа, который задается матрицей...

5
Эксперт С++
 Аватар для valeriikozlov
4728 / 2549 / 757
Регистрация: 18.08.2009
Сообщений: 4,568
24.02.2013, 19:08
можно например так (работает для количества вершин не более 100 и неориентированного графа):
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
#include <iostream>
using namespace std;
#define N 100
int main ()
{   
    int a[N][N], i, q[N], b[N]={0}, i_st, i_end, n;
    bool fl=true;
    cout<<"kol-vo vershin:  ";
    cin>>n;
    // здесь делаете заполнение графа смежности нулями и единицами (0 - нет пути, 1 - есть пусть)
    while(true)
    {
        for(i=0; i<n; i++)
            if(b[i]==0)
            {
                b[i]=1;
                q[0]=i;
                break;
            }
        if(i==n)
            break;
        i_st=0; i_end=1;
        while(i_st<i_end)
        {
            for(i=0; i<n; i++)
                if(a[q[i_st]][i] && q[i_st]!=i)
                {
                    if(b[i]==0)
                    {
                        q[i_end++]=i;
                        if(b[q[i_st]]==1)
                            b[i]=2;
                        else
                            b[i]=1;
                    }
                    else
                    {
                        if(b[q[i_st]]==b[i])
                            fl=false;                   
                    }
                }
            i_st++;
        }
    }
    if(fl) cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
    return 0;
}
0
1 / 1 / 3
Регистрация: 02.02.2012
Сообщений: 73
25.02.2013, 14:04  [ТС]
А если граф ориентированный?
0
Эксперт С++
 Аватар для valeriikozlov
4728 / 2549 / 757
Регистрация: 18.08.2009
Сообщений: 4,568
26.02.2013, 06:46
Цитата Сообщение от СергейАС Посмотреть сообщение
А если граф ориентированный?
если ориентированный, то можно так:
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
#include <iostream>
using namespace std;
#define N 100
int main ()
{   
    int a[N][N], i, q[N], b[N]={0}, i_st, i_end, n;
    bool fl=true;
    cout<<"kol-vo vershin:  ";
    cin>>n;
    // здесь делаете заполнение графа смежности нулями и единицами (0 - нет пути, 1 - есть пусть)
    while(true)
    {
        for(i=0; i<n; i++)
            if(b[i]==0)
            {
                b[i]=1;
                q[0]=i;
                break;
            }
        if(i==n)
            break;
        i_st=0; i_end=1;
        while(i_st<i_end)
        {
            for(i=0; i<n; i++)
                if((a[q[i_st]][i] || a[i][q[i_st]]) && q[i_st]!=i)
                {
                    if(b[i]==0)
                    {
                        q[i_end++]=i;
                        if(b[q[i_st]]==1)
                            b[i]=2;
                        else
                            b[i]=1;
                    }
                    else
                    {
                        if(b[q[i_st]]==b[i])
                            fl=false;                   
                    }
                }
            i_st++;
        }
    }
    if(fl) cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
    return 0;
}
0
1 / 1 / 3
Регистрация: 02.02.2012
Сообщений: 73
28.02.2013, 15:40  [ТС]
Ну в общем я пишу в графическом интерфейсе(VS 2010) и вот что получилось в форме(вместе с выводом графа на экран):Но этот код неправильно работает, подскажите пожалуйста где ошибка. Спасибо!!!
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
#pragma once
#include <time.h>
#include <Windows.h>
#include <math.h>
#include <stdio.h>
#include "GlobalVars.h"
 
namespace print_graf {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
 
    /// <summary>
    /// Сводка для Form1
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
        }
 
    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Panel^  panel1;
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::GroupBox^  groupBox1;
    private: System::Windows::Forms::Button^  button2;
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::Label^  label1;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown2;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown1;
    private: System::Windows::Forms::Button^  button3;
    private: System::Windows::Forms::Label^  label3;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown3;
    private: System::Windows::Forms::GroupBox^  groupBox2;
    private: System::Windows::Forms::Button^  button4;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown5;
    private: System::Windows::Forms::Label^  label5;
    private: System::Windows::Forms::NumericUpDown^  numericUpDown4;
    private: System::Windows::Forms::Label^  label4;
 
    private: System::Windows::Forms::Button^  button5;
    private: System::Windows::Forms::Label^  label6;
 
    protected: 
 
    private:
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Обязательный метод для поддержки конструктора - не изменяйте
        /// содержимое данного метода при помощи редактора кода.
        /// </summary>
        void InitializeComponent(void)
        {
            this->panel1 = (gcnew System::Windows::Forms::Panel());
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
            this->label3 = (gcnew System::Windows::Forms::Label());
            this->numericUpDown3 = (gcnew System::Windows::Forms::NumericUpDown());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->numericUpDown2 = (gcnew System::Windows::Forms::NumericUpDown());
            this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown());
            this->button3 = (gcnew System::Windows::Forms::Button());
            this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());
            this->button4 = (gcnew System::Windows::Forms::Button());
            this->numericUpDown5 = (gcnew System::Windows::Forms::NumericUpDown());
            this->label5 = (gcnew System::Windows::Forms::Label());
            this->numericUpDown4 = (gcnew System::Windows::Forms::NumericUpDown());
            this->label4 = (gcnew System::Windows::Forms::Label());
            this->button5 = (gcnew System::Windows::Forms::Button());
            this->label6 = (gcnew System::Windows::Forms::Label());
            this->groupBox1->SuspendLayout();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown3))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown2))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown1))->BeginInit();
            this->groupBox2->SuspendLayout();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown5))->BeginInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown4))->BeginInit();
            this->SuspendLayout();
            // 
            // panel1
            // 
            this->panel1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) 
                | System::Windows::Forms::AnchorStyles::Left) 
                | System::Windows::Forms::AnchorStyles::Right));
            this->panel1->BackColor = System::Drawing::Color::White;
            this->panel1->Location = System::Drawing::Point(13, 13);
            this->panel1->Name = L"panel1";
            this->panel1->Size = System::Drawing::Size(498, 492);
            this->panel1->TabIndex = 0;
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(540, 13);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(198, 30);
            this->button1->TabIndex = 1;
            this->button1->Text = L"Вывод графа";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            // 
            // groupBox1
            // 
            this->groupBox1->Controls->Add(this->label3);
            this->groupBox1->Controls->Add(this->numericUpDown3);
            this->groupBox1->Controls->Add(this->button2);
            this->groupBox1->Controls->Add(this->label2);
            this->groupBox1->Controls->Add(this->label1);
            this->groupBox1->Controls->Add(this->numericUpDown2);
            this->groupBox1->Controls->Add(this->numericUpDown1);
            this->groupBox1->Location = System::Drawing::Point(540, 70);
            this->groupBox1->Name = L"groupBox1";
            this->groupBox1->Size = System::Drawing::Size(200, 145);
            this->groupBox1->TabIndex = 2;
            this->groupBox1->TabStop = false;
            this->groupBox1->Text = L"Добавление ребра";
            // 
            // label3
            // 
            this->label3->AutoSize = true;
            this->label3->Location = System::Drawing::Point(71, 63);
            this->label3->Name = L"label3";
            this->label3->Size = System::Drawing::Size(59, 13);
            this->label3->TabIndex = 6;
            this->label3->Text = L"Вес ребра";
            // 
            // numericUpDown3
            // 
            this->numericUpDown3->Location = System::Drawing::Point(6, 82);
            this->numericUpDown3->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {100000, 0, 0, 0});
            this->numericUpDown3->Name = L"numericUpDown3";
            this->numericUpDown3->Size = System::Drawing::Size(187, 20);
            this->numericUpDown3->TabIndex = 5;
            // 
            // button2
            // 
            this->button2->Location = System::Drawing::Point(6, 108);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(187, 30);
            this->button2->TabIndex = 4;
            this->button2->Text = L"Добавить";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
            // 
            // label2
            // 
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(130, 19);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(22, 13);
            this->label2->TabIndex = 3;
            this->label2->Text = L"До";
            // 
            // label1
            // 
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(7, 20);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(20, 13);
            this->label1->TabIndex = 2;
            this->label1->Text = L"От";
            // 
            // numericUpDown2
            // 
            this->numericUpDown2->Location = System::Drawing::Point(130, 36);
            this->numericUpDown2->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {99, 0, 0, 0});
            this->numericUpDown2->Name = L"numericUpDown2";
            this->numericUpDown2->Size = System::Drawing::Size(64, 20);
            this->numericUpDown2->TabIndex = 1;
            // 
            // numericUpDown1
            // 
            this->numericUpDown1->Location = System::Drawing::Point(6, 36);
            this->numericUpDown1->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {99, 0, 0, 0});
            this->numericUpDown1->Name = L"numericUpDown1";
            this->numericUpDown1->Size = System::Drawing::Size(63, 20);
            this->numericUpDown1->TabIndex = 0;
            // 
            // button3
            // 
            this->button3->Location = System::Drawing::Point(540, 383);
            this->button3->Name = L"button3";
            this->button3->Size = System::Drawing::Size(198, 30);
            this->button3->TabIndex = 3;
            this->button3->Text = L"Сохранить в файл";
            this->button3->UseVisualStyleBackColor = true;
            this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
            // 
            // groupBox2
            // 
            this->groupBox2->Controls->Add(this->button4);
            this->groupBox2->Controls->Add(this->numericUpDown5);
            this->groupBox2->Controls->Add(this->label5);
            this->groupBox2->Controls->Add(this->numericUpDown4);
            this->groupBox2->Controls->Add(this->label4);
            this->groupBox2->Location = System::Drawing::Point(540, 241);
            this->groupBox2->Name = L"groupBox2";
            this->groupBox2->Size = System::Drawing::Size(200, 104);
            this->groupBox2->TabIndex = 4;
            this->groupBox2->TabStop = false;
            this->groupBox2->Text = L"Удаление ребра";
            // 
            // button4
            // 
            this->button4->Location = System::Drawing::Point(6, 63);
            this->button4->Name = L"button4";
            this->button4->Size = System::Drawing::Size(187, 30);
            this->button4->TabIndex = 4;
            this->button4->Text = L"Удалить";
            this->button4->UseVisualStyleBackColor = true;
            this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);
            // 
            // numericUpDown5
            // 
            this->numericUpDown5->Location = System::Drawing::Point(130, 37);
            this->numericUpDown5->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {99, 0, 0, 0});
            this->numericUpDown5->Name = L"numericUpDown5";
            this->numericUpDown5->Size = System::Drawing::Size(64, 20);
            this->numericUpDown5->TabIndex = 3;
            // 
            // label5
            // 
            this->label5->AutoSize = true;
            this->label5->Location = System::Drawing::Point(130, 20);
            this->label5->Name = L"label5";
            this->label5->Size = System::Drawing::Size(22, 13);
            this->label5->TabIndex = 2;
            this->label5->Text = L"До";
            // 
            // numericUpDown4
            // 
            this->numericUpDown4->Location = System::Drawing::Point(7, 37);
            this->numericUpDown4->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {99, 0, 0, 0});
            this->numericUpDown4->Name = L"numericUpDown4";
            this->numericUpDown4->Size = System::Drawing::Size(62, 20);
            this->numericUpDown4->TabIndex = 1;
            // 
            // label4
            // 
            this->label4->AutoSize = true;
            this->label4->Location = System::Drawing::Point(7, 20);
            this->label4->Name = L"label4";
            this->label4->Size = System::Drawing::Size(20, 13);
            this->label4->TabIndex = 0;
            this->label4->Text = L"От";
            // 
            // button5
            // 
            this->button5->Location = System::Drawing::Point(540, 430);
            this->button5->Name = L"button5";
            this->button5->Size = System::Drawing::Size(198, 31);
            this->button5->TabIndex = 7;
            this->button5->Text = L"Граф двудольный\?";
            this->button5->UseVisualStyleBackColor = true;
            this->button5->Click += gcnew System::EventHandler(this, &Form1::button5_Click);
            // 
            // label6
            // 
            this->label6->AutoSize = true;
            this->label6->Location = System::Drawing::Point(629, 475);
            this->label6->Name = L"label6";
            this->label6->Size = System::Drawing::Size(12, 13);
            this->label6->TabIndex = 8;
            this->label6->Text = L"/";
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(748, 513);
            this->Controls->Add(this->label6);
            this->Controls->Add(this->button5);
            this->Controls->Add(this->groupBox2);
            this->Controls->Add(this->button3);
            this->Controls->Add(this->groupBox1);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->panel1);
            this->Name = L"Form1";
            this->Text = L"Рисование графа";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            this->groupBox1->ResumeLayout(false);
            this->groupBox1->PerformLayout();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown3))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown2))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown1))->EndInit();
            this->groupBox2->ResumeLayout(false);
            this->groupBox2->PerformLayout();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown5))->EndInit();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->numericUpDown4))->EndInit();
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
 
    int koll_el;
 
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
    koll_el=0;
    FILE *f1;
    
        int i=0,j=0,x=0,y=0,ves=0,max_x=-1,max_y=-1;
        for(i=0;i<100;i++)
            for(j=0;j<100;j++)
                graf[i][j]=-1;
        if((f1 = fopen("input.txt","r"))!=NULL)
        {
        try
        {
        
        for(i=0;i<10000;i++)
            {
                if(fscanf(f1,"%d",&x)==EOF)
                    break;
                if(x>max_x)
                    max_x=x;
                if(fscanf(f1,"%d",&y)==EOF)
                    break;
                if(y>max_y)
                    max_y=y;
                if(fscanf(f1,"%d",&ves)==EOF)
                    break;
                graf[x][y]=ves;
            }
 
        if(max_x>max_y)
            koll_el=max_x+1;
        else
            koll_el=max_y+1;
        fclose(f1);
        }
    catch(...)
        {fclose(f1);}
        }
    }
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
             
             /*
             srand(time(NULL));
             n=rand()%N;
             g->DrawEllipse(blackPen,250,200,100,100);
             */
             int max_x=0,max_y=0;
             for(int i=0;i<100;i++)
                 for(int j=0;j<100;j++)
                 {
                     if(graf[i][j]!=-1)
                     {
                         if(i>max_x)
                             max_x=i;
                         if(j>max_y)
                             max_y=j;
                     }
                 }
             if(max_x>max_y)
                 koll_el=max_x+1;
             else
                 koll_el=max_y+1;
 
             Point p1;
             Point p2;
             PointF Location;
             System::Drawing::Font^Font;
             double pi = 3.14159265359;
             int n =koll_el;
             //n=10;
             double k;
             k=(n*8.4)/10;
             double x = 150,y = 200;
             IntPtr hwnd = panel1->Handle;
             Graphics^ g = Graphics::FromHwnd( hwnd );
             Brush ^brush = gcnew SolidBrush(Color::White);
             Pen ^blackPen = gcnew Pen(Color::Black);
             Pen ^redPen = gcnew Pen(Color::Red,2);
             g->FillRectangle(brush,RectangleF(0,0,panel1->Width,panel1->Height));
 
             /*---Отрисовка вершин---*/
             for(double i = 0; i < n; i++)
             {
                 x = 100 * cos (i/(n-k))+200;
                 y = 100 * sin (i/(n-k))+200;
 
                 if(x<250)
                     x-=15;
                 if(y<200)
                     y-=15;
 
                 g->DrawString(Convert::ToString(i), Font = (gcnew System::Drawing::Font(L"Arial", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,static_cast<System::Byte>(0))), brush=gcnew SolidBrush(Color::Black),Location= System::Drawing::Point(x+2,y+3));
                 
                 g->DrawEllipse(blackPen,x,y,18,18);
             }
 
             for(int i=0;i<100;i++)
                 for(int j=0;j<100;j++)
                 {
                     if(graf[i][j]!=-1&&i!=j)
                     {
                         p1=Point(
                                     x = 100 * cos (i/(n-k))+200,
                                     y = 100 * sin (i/(n-k))+200
                                 );
                         p2=Point(
                                     x = 100 * cos (j/(n-k))+200,
                                     y = 100 * sin (j/(n-k))+200
                                 );
                         g->DrawLine(blackPen,p1,p2);
                        // g->DrawEllipse(redPen,x,y,4,4);
                           
                         
                    /////////////////////////////////////////
                   //---------отрисовка направления-------//
                  /////////////////////////////////////////
 
                         double xs,xf,ys,yf,dx,dy;
                          xs = (100 * cos (i/(n-k))+200);
                          ys = (100 * sin (i/(n-k))+200);
                          xf = (100 * cos (j/(n-k))+200);
                          yf = (100 * sin (j/(n-k))+200);
                         
                         if((xs<xf)&&(ys<yf))
                         {
                            /*---1---*/
                             dx=xf-xs;
                             dy=yf-ys;
                             dx/=3;
                             dy/=3;
 
                             xs=xf-dx;
                             ys=yf-dy;
 
                         }
                         if((xs>xf)&&(ys<yf))
                         {
                            /*---3---*/
                             dx=xs-xf;
                             dy=yf-ys;
                             dx/=3;
                             dy/=3;
 
                             xs=xf+dx;
                             ys=yf-dy;
                         }
                         if((xs<xf)&&(ys>yf))
                         { 
                            /*---2---*/
                             dx=xf-xs;
                             dy=ys-yf;
                             dx/=3;
                             dy/=3;
 
 
                             xs=xf-dx;
                             ys=yf+dy;
                         }
                         if((xs>xf)&&(ys>yf))
                         {
                            /*---4---*/
                             dx=xs-xf;
                             dy=ys-yf;
                             dx/=3;
                             dy/=3;
 
                             xs=xf+dx;
                             ys=yf+dy;
                         }
                         p1=Point(xs,ys);
 
                         p2=Point(
                                     xf,
                                     yf
                                 );
                         g->DrawLine(redPen,p1,p2);
                //-------------------------------------/*/
 
                     }
                     if(graf[i][j]!=-1&&i==j)
                     {
                          x = 100 * cos (i/(n-k))+200;
                          y = 100 * sin (i/(n-k))+200;
                          if(x<250)
                              x-=15;
                          if(y<200)
                              y-=15;
                          g->DrawEllipse(redPen,x,y,18,18);
                     }
 
                 }
                 
             }
    private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
                FILE *f1;
                f1 = fopen("input.txt","w");
                for(int i=0;i<100;i++)
                    for(int j=0;j<100;j++)
                    {
                        if(graf[i][j]!=-1)
                        {
                            fprintf(f1,"%d\n",i);
                            fprintf(f1,"%d\n",j);
                            fprintf(f1,"%d\n",graf[i][j]);
                        }
                    }
                fclose(f1);
             }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
             int i,j;
             i = Decimal::ToInt32(this->numericUpDown1->Value);
             j = Decimal::ToInt32(this->numericUpDown2->Value);
             graf[i][j] = Decimal::ToInt32(this->numericUpDown3->Value);
         }
private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e) {
             int i,j;
             i = Decimal::ToInt32(this->numericUpDown4->Value);
             j = Decimal::ToInt32(this->numericUpDown5->Value);
             graf[i][j] = -1;
         }
private: System::Void textBox1_TextChanged(System::Object^  sender, System::EventArgs^  e) {
         }
private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e) {
    bool fl=true;
    while(true)
    {
        int i;
        for(i=0; i<koll_el; i++)
            if(b[i]==0)
            {
                b[i]=1;
                q[0]=i;
                break;
            }
        if(i==koll_el)
            break;
        i_st=0; i_end=1;
        while(i_st<i_end)
        {
            for(i=0; i<koll_el; i++)
                if(graf[q[i_st]][i] && q[i_st]!=i)
                {
                    if(b[i]==0)
                    {
                        q[i_end++]=i;
                        if(b[q[i_st]]==1)
                            b[i]=2;
                        else
                            b[i]=1;
                    }
                    else
                    {
                        if(b[q[i_st]]==b[i])
                            fl=false;                   
                    }
                }
            i_st++;
        }
    }
    if(fl)
        this->label6->Text = L"Да";
    else
        this->label6->Text = L"Нет";
         }
};
}
0
 Аватар для sunjan
12 / 7 / 7
Регистрация: 02.04.2014
Сообщений: 342
05.10.2015, 18:10
Что это за метод?Я что-то не понял
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
05.10.2015, 18:10
Помогаю со студенческими работами здесь

Неориентированный граф задан матрицей смежности. Найдите степени всех вершин графа
Работа с графами. Совсем не шарю в них. Может кто то поможет написать программу. Только с комментариями пожалуйста. Постановка задачи: ...

По заданной квадратной матрице из нулей и единиц определите, может ли данная матрица быть матрицей смежности простого неориентированного графа
помогите решить вот такую задачу пожалуйста(( По заданной квадратной матрице n*n из нулей и единиц определите, может ли данная матрица...

Функция DFS для графа, заданного списком смежности в main
Здравствуйте! Интересует такой вопрос. У меня есть граф, заданный списком смежности. Я хочу написать поиск в глубину, но нужно обращение к...

Составить программу, находящую разложение орграфа, заданного матрицей смежности, на компоненты методом Мальгранжа.
Составить программу, находящую разложение орграфа, заданного матрицей смежности, на компоненты методом Мальгранжа. матрица: 000010 ...

Постройте каркас минимального веса для графа заданного матрицей весов
Постройте каркас минимального веса для графа заданного матрицей весов(2 балла) помогите срочно плиз


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

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
SDL3 для Android: Загрузка PNG с альфа-каналом с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru