반응형

문제 출처 :


https://www.acmicpc.net/problem/11657



알고리즘 분석 :


문제 해결에 필요한 사항

1. 벨만 포드 알고리즘


벨만 포드 개념 :: http://www.crocus.co.kr/534

벨만 포드 소스 코드 :: http://www.crocus.co.kr/535


음의 가중치가 있으니 다익스트라는 아니다.


그렇다면 벨만 포드 혹은 플로이드 워셜인데


시간 복잡도를 확인해 보면


플로이드 워셜 :: O(|V|^3) = 125,000,000 >> 시간 초과

벨만 포드 :: O(|E|*|V|) = 3,000,000 따라서 벨만 포드를 이용하기로 한다.


기존 코드대로 한다면 인덱스가 1번부터 시작되는 문제이기에


int *dist = (int*)malloc(sizeof(int)*V); // int dist[V]과 같다.

이것을

 


int *dist = (int*)malloc(sizeof(int)*(+ 1))// int dist[V]과 같다.

이런식으로 바꾸어 주어야 한다.



int *dist = (int*)malloc(sizeof(int)*+ 1); // int dist[V]과 같다.

이렇게 해도 통과가 되지만, 이건 컴파일러에 따라 다르므로 이런식으로는 코딩을 하지 않는다.


소스 코드 : 



--------------------- 2017.12.10 벨만포드 알고리즘 재 적용 ------------------------


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
#include <iostream>
#include <cstdio>
#include <vector>
 
using namespace std;
 
typedef pair<intint> pii;
 
const int INF = 987654321;
 
vector<pii> adj[502];
int dist[502];
bool visit[502];
 
int main()
{
    int V, E;
    scanf("%d %d"&V, &E);
 
    for (int i = 0; i < E; i++)
    {
        int from, to, val;
        scanf("%d %d %d"&from, &to, &val);
 
        adj[from].push_back({ to, val });
    }
 
    fill(dist, dist + 502, INF);
    dist[1= 0;
 
    int n = 0;
    while (n <= V)
    {
        for (int i = 1; i <= V; i++)
        {
            int here = i;
            int cost = dist[here];
            int len = adj[i].size();
            for (int j = 0; j < len; j++)
            {
                int next = adj[here][j].first;
                int nextCost = adj[here][j].second + dist[here];
 
                if (dist[next] > nextCost)
                {
                    if (n == V)
                    {
                        printf("-1\n");
                        return 0;
                    }
                    dist[next] = nextCost;
                }
            }
        }
        n++;
    }
 
    for (int i = 2; i <= V; i++)
    {
        if (dist[i] == INF)
            printf("-1\n");
        else
            printf("%d\n", dist[i]);
    }
    return 0;
}
 
Crocus


-------------------------------




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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
 
// 간선 구조체
// src = 시작점, dest = 도착점, weight = 가중치
struct Edge
{
    int src, dest, weight;
};
 
// 그래프 구조체
// V :: 정점의 수 E :: 간선의 수
// edge :: 포인터 형식으로 서로 다른 정점을 연결하기 위해 존재
struct Graph
{
    int V, E;
 
    struct Edge* edge;
};
 
// V와 E를 통해 정점과 간선의 수를 가진 그래프를 생성한다.
struct Graph* createGraph(int V, int E)
{
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
 
    graph->= V;
    graph->= E;
 
    graph->edge = (struct Edge*) malloc(graph->* sizeof(struct Edge));
 
    return graph;
}
 
// 결과를 출력하기 위한 함수
void printArr(int dist[], int n)
{
    for (int i = 2; i <= n; ++i)
        dist[i] == INT_MAX ? printf("-1\n") : printf("%d\n", dist[i]);
}
 
// src에서 모든 다른 정점까지의 최단 거리를 찾아주는 BellmanFord 함수이다.
// 음의 가중치 까지 적용이 가능하다.
void BellmanFord(struct Graph* graph, int src)
{
    int V = graph->V;
    int E = graph->E;
    int *dist = (int*)malloc(sizeof(int)*(+ 1)); // int dist[V]과 같다.
 
    // 모든 최단 거리를 무한대로 지정해주고, 시작점(src)만 0으로 초기화 한다.
    for (int i = 0; i <= V; i++)
        dist[i] = INT_MAX;
    
    dist[src] = 0;
 
    // 벨만 포드 알고리즘
    for (int i = 1; i <= V - 1; i++)
    {
        for (int j = 0; j < E; j++)
        {
            int u = graph->edge[j].src;
            int v = graph->edge[j].dest;
            int weight = graph->edge[j].weight;
            // 정점u가(시작점이) 무한대가 아니고, 
            // 시작점까지의 최단 거리 + 가중치가 도착점의 가중치 
            // 보다 작을 때 업데이트 해준다.
            if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
                dist[v] = dist[u] + weight;
        }
    }
 
    // 음의 가중치 때문에 무한히 최단 경로가 작아지는 것이 있다면
    // 탐색하여 알려준다.
    for (int i = 0; i < E; i++)
    {
        int u = graph->edge[i].src;
        int v = graph->edge[i].dest;
        int weight = graph->edge[i].weight;
        // if문에서 현재위치 최단거리 + 가중치가 계속해서 더 작아질 경우
        // 음의 사이클이 있다고 판단한다.
        if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
        {
            printf("-1");
            return;
        }
    }
 
    printArr(dist, V);
 
    return;
}
 
int main()
{
    int V; // 정점의 수
    int E; // 간선의 수
 
    scanf("%d %d"&V, &E);
 
    struct Graph* graph = createGraph(V, E);
 
    // 그래프 정보를 입력해준다.
    for (int i = 0; i < E; i++)
        scanf("%d %d %d"&graph->edge[i].src, &graph->edge[i].dest, &graph->edge[i].weight);
 
 
    BellmanFord(graph, 1);
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형