그래프/DFS

칵테일

4gats 2023. 8. 19. 15:20

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

 

1033번: 칵테일

august14는 세상에서 가장 맛있는 칵테일이다. 이 칵테일을 만드는 정확한 방법은 아직 세상에 공개되지 않았지만, 들어가는 재료 N개는 공개되어 있다.  경근이는 인터넷 검색을 통해서 재료 쌍 N

www.acmicpc.net

일단 비율들을 가지고 최소공배수를 구한다.

그리고 그 최소공배수를 ans[0]에 박고,

DFS로 순회를 하면서 비율을 곱하면서 업데이트 해준다.

 

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
#include <iostream>
#include <vector>
#include <tuple>
 
using namespace std;
 
vector<tuple<intintint>> A[10];
long lcm;
bool visited[10];
long ans[10];
 
long gcd(long a, long b)
{
    if (b == 0)
    {
        return a;
    }
    else
    {
        return gcd(b, a % b);
    }
}
 
void DFS(int node)
{
    visited[node] = true;
 
    for (tuple<intintint> i : A[node])
    {
        int next = get<0>(i);
        if (!visited[next])
        {
            // 주어진 비율로 다음 노드값 업데이트
            ans[next] = ans[node] * get<2>(i) / get<1>(i);
            DFS(next);
        }
    }
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int n;
    cin >> n;
    lcm = 1;
    
    for (int i = 0; i < n - 1; i++)
    {
        int a, b, p, q;
        cin >> a >> b >> p >> q;
 
        //순서 주의!!
        A[a].push_back(make_tuple(b, p, q));
        A[b].push_back(make_tuple(a, q, p));
        
        // 두 수의 최소 공배수는 두 수의 곱을 최대공약수로 나눈 것
        lcm *= (p * q / gcd(p, q));
    }
 
    ans[0= lcm;
    DFS(0);
 
    // 여러 개의 최대 공약수 구하기
    long mgcd = ans[0];
    for (int i = 1; i < n; i++)
    {
        mgcd = gcd(mgcd, ans[i]);
    }
 
    for (int i = 0; i < n; i++)
    {
        cout << ans[i] / mgcd << ' ';
    }
    
    return 0;
}
cs

 

이때, 필요한 재료의 질량을 모두 더한 값이 최소가 되어야 한다.

그러므로, ans의 값에서 최대공약수를 구해서

최대공약수로 나눈 값을 출력해야한다.