Advertisement
Guest User

Untitled

a guest
May 26th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 19.33 KB | None | 0 0
  1. #pragma once
  2. //#include "stdafx.h"
  3. #include <iostream>
  4. #include <typeinfo>
  5. #include <vector>
  6. #include <limits>
  7. #include <list>
  8. #include <iterator>
  9. namespace Project2 {
  10.  
  11.     using namespace System;
  12.     using namespace System::ComponentModel;
  13.     using namespace System::Collections;
  14.     using namespace System::Windows::Forms;
  15.     using namespace System::Data;
  16.     using namespace System::Drawing;
  17.     using namespace std;
  18.  
  19.     //Определяем свои типы - пара двух числе будет называться PInt pair int
  20.     typedef pair<int, int> PInt;
  21.  
  22.     //Вектор чисел будет называться VInt(логично, не правда ли?) vector int
  23.     typedef vector<int> VInt;
  24.  
  25.     //Вектор интовых векторов будет называться VVInt
  26.     typedef vector<VInt> VVInt;
  27.     //Вектор интовых пар будет называться VPInt
  28.     typedef vector<PInt> VPInt;
  29.  
  30.     const int inf = numeric_limits<int>::max();
  31.  
  32.     /*
  33.     * Решает задачу о назначениях Венгерским методом.
  34.     * matrix: прямоугольная матрица из целых чисел (не обязательно положительных).
  35.     *         Высота матрицы должна быть не больше ширины.
  36.     * Возвращает: Список выбранных элементов, по одному из каждой строки матрицы.
  37.     */
  38.  
  39.     /// <summary>
  40.     /// Summary for MyForm
  41.     /// </summary>
  42.     //Генерация формы - создано автоматически
  43.     public ref class MyForm : public System::Windows::Forms::Form
  44.     {
  45.     public:
  46.         MyForm(void)
  47.         {
  48.             InitializeComponent();
  49.             //
  50.             //TODO: Add the constructor code here
  51.             //
  52.         }
  53.  
  54.     protected:
  55.         /// <summary>
  56.         /// Clean up any resources being used.
  57.         /// </summary>
  58.         ~MyForm()
  59.         {
  60.             if (components)
  61.             {
  62.                 delete components;
  63.             }
  64.         }
  65.     private: System::Windows::Forms::DataGridView^  dataGridView1;
  66.     protected:
  67.     private: System::Windows::Forms::Button^  button1;
  68.     private: System::Windows::Forms::NumericUpDown^  Col1;
  69.  
  70.     private: System::Windows::Forms::NumericUpDown^  Col2;
  71.  
  72.     private: System::Windows::Forms::Label^  label1;
  73.     private: System::Windows::Forms::Label^  label2;
  74.     private: System::Windows::Forms::TextBox^  resultTextBox;
  75.     private: System::Windows::Forms::TabControl^  tabControl1;
  76.     private: System::Windows::Forms::TabPage^  MainAlghoritm;
  77.  
  78.     private: System::Windows::Forms::TabPage^  tabPage2;
  79.     private: System::Windows::Forms::TabPage^  tabPage3;
  80.     private: System::Windows::Forms::TextBox^  textBox1;
  81.     private: System::Windows::Forms::TextBox^  textBox2;
  82.  
  83.  
  84.  
  85.     private:
  86.         /// <summary>
  87.         /// Required designer variable.
  88.         /// </summary>
  89.         System::ComponentModel::Container ^components;
  90.  
  91. #pragma region Windows Form Designer generated code
  92.         /// <summary>
  93.         /// Required method for Designer support - do not modify
  94.         /// the contents of this method with the code editor.
  95.         /// </summary>
  96.         void InitializeComponent(void)
  97.         {
  98.             this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView());
  99.             this->button1 = (gcnew System::Windows::Forms::Button());
  100.             this->Col1 = (gcnew System::Windows::Forms::NumericUpDown());
  101.             this->Col2 = (gcnew System::Windows::Forms::NumericUpDown());
  102.             this->label1 = (gcnew System::Windows::Forms::Label());
  103.             this->label2 = (gcnew System::Windows::Forms::Label());
  104.             this->resultTextBox = (gcnew System::Windows::Forms::TextBox());
  105.             this->tabControl1 = (gcnew System::Windows::Forms::TabControl());
  106.             this->MainAlghoritm = (gcnew System::Windows::Forms::TabPage());
  107.             this->tabPage2 = (gcnew System::Windows::Forms::TabPage());
  108.             this->tabPage3 = (gcnew System::Windows::Forms::TabPage());
  109.             this->textBox1 = (gcnew System::Windows::Forms::TextBox());
  110.             this->textBox2 = (gcnew System::Windows::Forms::TextBox());
  111.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->BeginInit();
  112.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->Col1))->BeginInit();
  113.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->Col2))->BeginInit();
  114.             this->tabControl1->SuspendLayout();
  115.             this->MainAlghoritm->SuspendLayout();
  116.             this->tabPage2->SuspendLayout();
  117.             this->tabPage3->SuspendLayout();
  118.             this->SuspendLayout();
  119.             //
  120.             // dataGridView1
  121.             //
  122.             this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize;
  123.             this->dataGridView1->Location = System::Drawing::Point(17, 56);
  124.             this->dataGridView1->Name = L"dataGridView1";
  125.             this->dataGridView1->Size = System::Drawing::Size(549, 319);
  126.             this->dataGridView1->TabIndex = 0;
  127.             //
  128.             // button1
  129.             //
  130.             this->button1->Location = System::Drawing::Point(432, 395);
  131.             this->button1->Name = L"button1";
  132.             this->button1->Size = System::Drawing::Size(134, 23);
  133.             this->button1->TabIndex = 1;
  134.             this->button1->Text = L"Розрахунок";
  135.             this->button1->UseVisualStyleBackColor = true;
  136.             this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
  137.             //
  138.             // Col1
  139.             //
  140.             this->Col1->AccessibleName = L"Cols";
  141.             this->Col1->Location = System::Drawing::Point(17, 30);
  142.             this->Col1->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 30, 0, 0, 0 });
  143.             this->Col1->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 });
  144.             this->Col1->Name = L"Col1";
  145.             this->Col1->Size = System::Drawing::Size(120, 20);
  146.             this->Col1->TabIndex = 2;
  147.             this->Col1->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 });
  148.             this->Col1->ValueChanged += gcnew System::EventHandler(this, &MyForm::Col1_ValueChanged);
  149.             //
  150.             // Col2
  151.             //
  152.             this->Col2->AccessibleName = L"Rows";
  153.             this->Col2->Location = System::Drawing::Point(143, 30);
  154.             this->Col2->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 30, 0, 0, 0 });
  155.             this->Col2->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 });
  156.             this->Col2->Name = L"Col2";
  157.             this->Col2->Size = System::Drawing::Size(120, 20);
  158.             this->Col2->TabIndex = 3;
  159.             this->Col2->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 });
  160.             this->Col2->ValueChanged += gcnew System::EventHandler(this, &MyForm::Col1_ValueChanged);
  161.             //
  162.             // label1
  163.             //
  164.             this->label1->AutoSize = true;
  165.             this->label1->Location = System::Drawing::Point(14, 14);
  166.             this->label1->Name = L"label1";
  167.             this->label1->Size = System::Drawing::Size(55, 13);
  168.             this->label1->TabIndex = 4;
  169.             this->label1->Text = L"Стовбець";
  170.             this->label1->Click += gcnew System::EventHandler(this, &MyForm::label1_Click);
  171.             //
  172.             // label2
  173.             //
  174.             this->label2->AutoSize = true;
  175.             this->label2->Location = System::Drawing::Point(140, 14);
  176.             this->label2->Name = L"label2";
  177.             this->label2->Size = System::Drawing::Size(43, 13);
  178.             this->label2->TabIndex = 5;
  179.             this->label2->Text = L"Строка";
  180.             //
  181.             // resultTextBox
  182.             //
  183.             this->resultTextBox->Location = System::Drawing::Point(17, 398);
  184.             this->resultTextBox->Name = L"resultTextBox";
  185.             this->resultTextBox->Size = System::Drawing::Size(409, 20);
  186.             this->resultTextBox->TabIndex = 6;
  187.             //
  188.             // tabControl1
  189.             //
  190.             this->tabControl1->Controls->Add(this->MainAlghoritm);
  191.             this->tabControl1->Controls->Add(this->tabPage2);
  192.             this->tabControl1->Controls->Add(this->tabPage3);
  193.             this->tabControl1->Location = System::Drawing::Point(12, 12);
  194.             this->tabControl1->Name = L"tabControl1";
  195.             this->tabControl1->SelectedIndex = 0;
  196.             this->tabControl1->Size = System::Drawing::Size(599, 460);
  197.             this->tabControl1->TabIndex = 2;
  198.             this->tabControl1->Tag = L"";
  199.             //
  200.             // MainAlghoritm
  201.             //
  202.             this->MainAlghoritm->Controls->Add(this->button1);
  203.             this->MainAlghoritm->Controls->Add(this->label2);
  204.             this->MainAlghoritm->Controls->Add(this->resultTextBox);
  205.             this->MainAlghoritm->Controls->Add(this->label1);
  206.             this->MainAlghoritm->Controls->Add(this->Col2);
  207.             this->MainAlghoritm->Controls->Add(this->dataGridView1);
  208.             this->MainAlghoritm->Controls->Add(this->Col1);
  209.             this->MainAlghoritm->Location = System::Drawing::Point(4, 22);
  210.             this->MainAlghoritm->Name = L"MainAlghoritm";
  211.             this->MainAlghoritm->Padding = System::Windows::Forms::Padding(3);
  212.             this->MainAlghoritm->Size = System::Drawing::Size(591, 434);
  213.             this->MainAlghoritm->TabIndex = 0;
  214.             this->MainAlghoritm->Text = L"Основной алгоритм";
  215.             this->MainAlghoritm->UseVisualStyleBackColor = true;
  216.             //
  217.             // tabPage2
  218.             //
  219.             this->tabPage2->Controls->Add(this->textBox1);
  220.             this->tabPage2->Location = System::Drawing::Point(4, 22);
  221.             this->tabPage2->Name = L"tabPage2";
  222.             this->tabPage2->Padding = System::Windows::Forms::Padding(3);
  223.             this->tabPage2->Size = System::Drawing::Size(591, 434);
  224.             this->tabPage2->TabIndex = 1;
  225.             this->tabPage2->Text = L"Инструкция";
  226.             this->tabPage2->UseVisualStyleBackColor = true;
  227.             this->tabPage2->Click += gcnew System::EventHandler(this, &MyForm::tabPage2_Click);
  228.             //
  229.             // tabPage3
  230.             //
  231.             this->tabPage3->Controls->Add(this->textBox2);
  232.             this->tabPage3->Location = System::Drawing::Point(4, 22);
  233.             this->tabPage3->Name = L"tabPage3";
  234.             this->tabPage3->Padding = System::Windows::Forms::Padding(3);
  235.             this->tabPage3->Size = System::Drawing::Size(591, 434);
  236.             this->tabPage3->TabIndex = 2;
  237.             this->tabPage3->Text = L"О создателях";
  238.             this->tabPage3->UseVisualStyleBackColor = true;
  239.             //
  240.             // textBox1
  241.             //
  242.             this->textBox1->Location = System::Drawing::Point(16, 15);
  243.             this->textBox1->Multiline = true;
  244.             this->textBox1->Name = L"textBox1";
  245.             this->textBox1->ScrollBars = System::Windows::Forms::ScrollBars::Vertical;
  246.             this->textBox1->Size = System::Drawing::Size(556, 398);
  247.             this->textBox1->TabIndex = 0;
  248.             this->textBox1->Text = L"ИНСТРУКЦИЮ ПИСАТЬ СЮДАИНСТРУ\r\nКЦИЮ ПИСАТЬ СЮДАИНСТРУКЦИЮ ПИСАТЬ \r\nСЮДАИНСТРУКЦИЮ "
  249.                 L"ПИСАТЬ СЮДАИНСТРУКЦИЮ \r\nПИСАТЬ СЮДАИНСТРУКЦИЮ ПИСАТЬ СЮДАИНСТРУКЦИЮ \r\nПИСАТЬ \r\nС"
  250.                 L"ЮДА";
  251.             //
  252.             // textBox2
  253.             //
  254.             this->textBox2->Location = System::Drawing::Point(18, 15);
  255.             this->textBox2->Multiline = true;
  256.             this->textBox2->Name = L"textBox2";
  257.             this->textBox2->ScrollBars = System::Windows::Forms::ScrollBars::Vertical;
  258.             this->textBox2->Size = System::Drawing::Size(556, 398);
  259.             this->textBox2->TabIndex = 1;
  260.             this->textBox2->Text = L"ВОТ СЮДА НАПИШИ О СЕБЕ";
  261.             this->textBox2->TextChanged += gcnew System::EventHandler(this, &MyForm::textBox2_TextChanged);
  262.             //
  263.             // MyForm
  264.             //
  265.             this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
  266.             this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
  267.             this->ClientSize = System::Drawing::Size(623, 489);
  268.             this->Controls->Add(this->tabControl1);
  269.             this->Name = L"MyForm";
  270.             this->Text = L"Венгерский алгоритм\\Задача о назначениях";
  271.             this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
  272.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->EndInit();
  273.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->Col1))->EndInit();
  274.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->Col2))->EndInit();
  275.             this->tabControl1->ResumeLayout(false);
  276.             this->MainAlghoritm->ResumeLayout(false);
  277.             this->MainAlghoritm->PerformLayout();
  278.             this->tabPage2->ResumeLayout(false);
  279.             this->tabPage2->PerformLayout();
  280.             this->tabPage3->ResumeLayout(false);
  281.             this->tabPage3->PerformLayout();
  282.             this->ResumeLayout(false);
  283.  
  284.         }
  285. #pragma endregion
  286.     private: System::Void MyForm_Load(System::Object^  sender, System::EventArgs^  e) {
  287.     }
  288.     private: System::Void label1_Click(System::Object^  sender, System::EventArgs^  e) {
  289.     }
  290.  
  291. //Тут заканчивается автоматическая генерация формы конструктором
  292.  
  293.     //Основной алгоритм, производящий вычисления удачных пар по венгерскому алгоритму
  294.     private: VPInt hungarian(const VVInt &matrix){
  295.  
  296.                  // Размеры матрицы
  297.                  int height = matrix.size(), width = matrix[0].size();
  298.  
  299.                  // Значения, вычитаемые из строк (u) и столбцов (v)
  300.                  VInt u(height, 0), v(width, 0);
  301.  
  302.                  // Индекс помеченной клетки в каждом столбце
  303.                  VInt markIndices(width, -1);
  304.  
  305.                  // Будем добавлять строки матрицы одну за другой
  306.                  for (int i = 0; i < height; i++) {
  307.                      VInt links(width, -1);
  308.                      VInt mins(width, inf);
  309.                      VInt visited(width, 0);
  310.  
  311.                      // Разрешение коллизий (создание "чередующейся цепочки" из нулевых элементов)
  312.                      int markedI = i, markedJ = -1, j;
  313.                      while (markedI != -1) {
  314.                          // Обновим информацию о минимумах в посещенных строках непосещенных столбцов
  315.                          // Заодно поместим в j индекс непосещенного столбца с самым маленьким из них
  316.                          j = -1;
  317.                          for (int j1 = 0; j1 < width; j1++)
  318.                          if (!visited[j1]) {
  319.                              if (matrix[markedI][j1] - u[markedI] - v[j1] < mins[j1]) {
  320.                                  mins[j1] = matrix[markedI][j1] - u[markedI] - v[j1];
  321.                                  links[j1] = markedJ;
  322.                              }
  323.                              if (j == -1 || mins[j1] < mins[j]){}
  324.                              j = j1;
  325.                          }
  326.  
  327.                          // Теперь нас интересует элемент с индексами (markIndices[links[j]], j)
  328.                          // Произведем манипуляции со строками и столбцами так, чтобы он обнулился
  329.                          int delta = mins[j];
  330.                          for (int j1 = 0; j1 < width; j1++)
  331.                          if (visited[j1]) {
  332.                              u[markIndices[j1]] += delta;
  333.                              v[j1] -= delta;
  334.                          }
  335.                          else {
  336.                              mins[j1] -= delta;
  337.                          }
  338.                          u[i] += delta;
  339.  
  340.                          // Если коллизия не разрешена - перейдем к следующей итерации
  341.                          visited[j] = 1;
  342.                          markedJ = j;
  343.                          markedI = markIndices[j];
  344.                      }
  345.  
  346.                      // Пройдем по найденной чередующейся цепочке клеток, снимем отметки с
  347.                      // отмеченных клеток и поставим отметки на неотмеченные
  348.                      for (; links[j] != -1; j = links[j])
  349.                          markIndices[j] = markIndices[links[j]];
  350.                      markIndices[j] = i;
  351.                  }
  352.  
  353.                  // Вернем результат в естественной форме
  354.                  VPInt result;
  355.                  for (int j = 0; j < width; j++)
  356.                  if (markIndices[j] != -1)
  357.                      result.push_back(PInt(markIndices[j], j));
  358.                  return result;
  359.     }
  360.  
  361.     //Обработчик нажатия на кнопку
  362.     private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
  363.                  //Получаем размеры таблицы
  364.                  int sizeCols = Convert::ToInt32(Col1->Value);
  365.                  int sizeRows = Convert::ToInt32(Col2->Value);
  366.  
  367.                  //Проверяем что количество столбцов и колонок соответствует условиям задачи
  368.                  if (sizeRows > sizeCols)
  369.                  {
  370.                      //Если не соответствует выводим сообщение на экран и заканчиваем выполнение
  371.                      MessageBox::Show(this, "Number of cols must be greater or equals than number of rows", "My Application", MessageBoxButtons::OK, MessageBoxIcon::Asterisk);
  372.                      return;
  373.                  }
  374.  
  375.                  //Если дошли до сюда, значит по размерам матрицы все правильно
  376.                  //Создаем временный вектор в который будем аккумулировать данные из строк матрицы
  377.                  vector <int> tempVector;
  378.                  //Свой собственный переопределенный тип, представляющий собой вектор векторов
  379.                  VVInt solvingMatrix(0);
  380.  
  381.                  //Помещаем значения из таблицы во временный вектор
  382.                  for (int i = 0; i < sizeCols; i++){
  383.                      vector <int> tempVector;
  384.                      for (int j = 0; j < sizeRows; j++){
  385.                          //Помещаем тут из таблицы dataGridView1 колонки Rows[i] ячейки Cells[j] значение Value
  386.                          tempVector.insert(tempVector.end(), Convert::ToInt32(dataGridView1->Rows[i]->Cells[j]->Value));
  387.                      }
  388.                      //Передаем временный вектор внутрь матрицы, ставим его на позицию последнего в векторе - то есть он становится последним
  389.                      //Метод добавления принимает в себя два значения - куда вставлять и что вставлять, после того как строка набита в вектор,
  390.                      //Добавляем строку в вектор векторов VVInt
  391.                      solvingMatrix.insert(solvingMatrix.end(), tempVector);
  392.  
  393.  
  394.                      //Решаем нашу матрицу при помощи Венгерского алгоритма
  395.                      VPInt result = hungarian(solvingMatrix);
  396.  
  397.  
  398.                      //Выводим пары строка-столбец, которые решают нашу задачу
  399.                      for (int i = 0; i < result.size(); i++) {
  400.                          resultTextBox->Text += Convert::ToString(result[i].first + 1) + "-";
  401.                          resultTextBox->Text += Convert::ToString(result[i].second + 1) + "  ";
  402.                      }
  403.  
  404.                  }
  405.     }
  406.  
  407.              //Обработчик события - изменение значения переключаемых полей ввода размеров матрицы
  408.     private: System::Void Col1_ValueChanged(System::Object^  sender, System::EventArgs^  e) {
  409.                  //Получаем данные о размерах матрицы
  410.                  int sizeCols = Convert::ToInt32(Col1->Value);
  411.                  int sizeRows = Convert::ToInt32(Col2->Value);
  412.  
  413.                  //Создаем таблицу заданного размера
  414.                  dataGridView1->ColumnCount = sizeCols;
  415.                  dataGridView1->RowCount = sizeRows;
  416.  
  417.                  //Заполняем нулями ячейки если в них еще ничего не записано, если записано то не перезаполняем
  418.                  for (int i = 0; i < sizeCols; i++){
  419.                      for (int j = 0; j < sizeRows; j++){
  420.                          dataGridView1->Columns[i]->HeaderCell->Value = Convert::ToString(i + 1);
  421.                          dataGridView1->Rows[j]->HeaderCell->Value = Convert::ToString(j + 1);
  422.                          if (dataGridView1->Rows[j]->Cells[i]->Value == 0){
  423.                              dataGridView1->Rows[j]->Cells[i]->Value = 0;
  424.                          }
  425.                      }
  426.                  }
  427.  
  428.                  //Настраиваем отображение
  429.                  dataGridView1->AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders);                
  430.                  dataGridView1->AutoResizeColumns();
  431.     }
  432.     private: System::Void tabPage2_Click(System::Object^  sender, System::EventArgs^  e) {
  433.     }
  434. private: System::Void textBox2_TextChanged(System::Object^  sender, System::EventArgs^  e) {
  435. }
  436. };
  437. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement