Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 18.04.2024, 13:36   #1
Veronika360
 
Регистрация: 06.04.2024
Сообщений: 5
По умолчанию Алгоритм Дейкстры в С

our task is to construct an undirected graph without loops based on the list of edges given in the input and then perform the following operations on this graph according to the input:
i - insert - inserting a new edge into the graph
s - search - search for the shortest path in the graph according to the specified start and end
u - update - modification of an existing edge in the graph (i.e. modification of the weight of the given edge), while the weight of the edge must not be changed to a negative number
d - delete - remove an existing edge from the graph

An edge is defined as a pair of two vertices, while the vertices are numbered with non-negative whole numbers from 0 to N, where N is the maximum number of vertices in the given graph.

If the given operation fails, the error message " failed" is written in a separate line.
The failure is, for example, when we try to add an edge that already exists, or when the search operation did not find any path for a given pair of vertices.

The input of the program is the number N (max. number of vertices in the graph) followed by a space and the number M (number of edges in the initial graph) on the first line.
There are M lines, where in each line there is one edge of the initial graph, in the format "(vertex_1, vertex2, weight)".
This initial graph is followed by any number of lines, each line representing one command for one operation (ie, insert, search, update, or delete).
The operation is expressed by the initial letter, i.e. i, s, u or d. The following are the data required for the given operation.
The insert operation needs the following 3 data: vertex_1 number, vertex_2 number, edge weight (also an integer)
The search operation needs the following 2 data: the number of the starting vertex, the number of the end (target) vertex
The update operation needs the following 3 data: number of vertex_1, number of vertex_2, change of edge weight (also an integer)
The delete operation needs the following 2 data: vertex_1 number, vertex_2 number

The output is the shortest paths found by search operations, while the output format is as follows:
: [vertex1, vertex2, vertex3, ..., last_vertex]
In addition, the above-mentioned error messages are also output in case of operation failure, together with the edge above which the given operation failed.

Do 22.04.2024, 09:00

Ukážkový vstup
10 30
(5, 0, 116)
(5, 9, 163)
(5, 2, 117)
(5, 3, 110)
(5, 7, 169)
(5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5
i 5 2 44
d 1 2
s 5 7
u 0 3 42
u 5 6 56
u 2 6 17
s 9 6

Ukážkový výstup
283: [3, 1, 8]
110: [5, 3]
129: [3, 0]
214: [4, 0, 6]
309: [6, 3, 9]
163: [9, 5]
159: [2, 1]
117: [5, 2]
159: [1, 2]
309: [6, 3, 9]
180: [9, 3]
186: [4, 8, 3]
259: [5, 7, 4]
145: [4, 9]
187: [1, 8, 4]
195: [0, 1, 5]
85: [1, 5]
127: [5, 7]
157: [6, 7, 4]
215: [9, 4, 7]
194: [2, 8, 6, 7]
163: [9, 5]
121: [8, 9]
45: [3, 8, 6]
85: [1, 5]
update 8 6 failed
121: [8, 9]
117: [5, 2]
82: [7, 8, 1]
35: [6, 8, 7]
92: [3, 8, 1]
101: [0, 3]
35: [7, 8, 6]
75: [8, 2]
45: [3, 8, 6]
78: [3, 8, 7]
164: [5, 6, 0]
80: [4, 9]
117: [3, 8, 7, 4]
119: [2, 8, 3]
101: [9, 5, 6]
35: [6, 8, 7]
127: [7, 5]
86: [6, 0]
116: [0, 7, 5]
193: [0, 4, 9]
87: [8, 6, 0]
1: [6, 8]
119: [3, 8, 2]
update 8 3 failed
109: [4, 7, 6, 8, 3]
169: [9, 8, 1]
44: [8, 3]
177: [5, 7, 8, 3]
38: [7, 5]
38: [5, 7]
144: [9, 4, 7, 6]
Вложения
Тип файла: txt dijkstra.txt (9.6 Кб, 3 просмотров)
Veronika360 вне форума Ответить с цитированием
Старый 18.04.2024, 13:38   #2
Veronika360
 
Регистрация: 06.04.2024
Сообщений: 5
По умолчанию

Помогите с этим кодом, сверху написано задание, нужный ввод и нужный вывод, посоветовали добавить приоритетную очередь, но абсолютно никакая из моих версий не сработала
Veronika360 вне форума Ответить с цитированием
Старый 21.04.2024, 06:13   #3
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,291
По умолчанию

Лямзим код из статьи:
Код:
void queue_add(PQNode* pq, int* pqSize, int vertex, int dist)
{
    pq[*pqSize] = (PQNode){vertex, dist};
    (*pqSize)++;

    int i = *pqSize - 1;
    int parent = (i - 1) / 2;

    while (i > 0 && pq[parent].dist > pq[i].dist)
    {
        PQNode temp = pq[i];
        pq[i] = pq[parent];
        pq[parent] = temp;

        i = parent;
        parent = (i - 1) / 2;
    }
}

void heapify(PQNode* pq, int pqSize, int i)
{
    for (;;)
    {
        int leftChild = 2 * i + 1;
        int rightChild = 2 * i + 2;
        int smallestChild = i;

        if (leftChild < pqSize && pq[leftChild].dist < pq[smallestChild].dist)
            smallestChild = leftChild;

        if (rightChild < pqSize && pq[rightChild].dist < pq[smallestChild].dist)
            smallestChild = rightChild;

        if (smallestChild == i)
            break;

        PQNode temp = pq[i];
        pq[i] = pq[smallestChild];
        pq[smallestChild] = temp;
        i = smallestChild;
    }
}

PQNode queue_get(PQNode* pq, int* pqSize)
{
    PQNode result = pq[0];
    pq[0] = pq[*pqSize - 1];
    (*pqSize)--;
    heapify(pq, *pqSize, 0);
    return result;
}

// Dijkstra's algorithm to find the shortest path
void dijkstra(Graph* graph, int src, int dest) {
...
    // Enqueue source node into the priority queue
    queue_add(pq, &pqSize, src, 0);

    while (pqSize > 0) {
        // Extract minimum from priority queue (binary heap)
        PQNode min_node = queue_get(pq, &pqSize);

        int u = min_node.vertex;
        visited[u] = 1;

        // Relax adjacent vertices of u
        for (int i = 0; i < graph->nodes[u].num_edges; i++) {
            int v = graph->nodes[u].edges[i].dest;
            int weight = graph->nodes[u].edges[i].weight;
            if (!visited[v] && distances[u] != INT_MAX && distances[u] + weight < distances[v]) {
                distances[v] = distances[u] + weight;
                prev[v] = u;
                queue_add(pq, &pqSize, v, distances[v]);
            }
        }
    }
...
Вроде вывод не испортился.
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )
BDA на форуме Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Алгоритм Дейкстры Xopyc1996 Помощь студентам 0 05.05.2016 14:08
Алгоритм Дейкстры Малайка Общие вопросы Delphi 0 05.03.2016 20:45
Алгоритм Дейкстры Малайка Общие вопросы Delphi 3 13.02.2016 20:18
С. Алгоритм Дейкстры XeniaZharinova Помощь студентам 0 26.12.2013 12:36
Алгоритм Дейкстры в xml LENA_M HTML и CSS 0 29.05.2010 04:36