summaryrefslogtreecommitdiffstats
path: root/Main/C++/2016/S3.cpp
blob: c4ebe69792f5c07a7a2768e5e9b536c0be7fb0ab (plain)
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
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int N,M;
    cin >> N >> M;
    vector<int> pho_restaurants;
    int t;
    for (int i = 0; i < M; i++)
    {

        cin >> t;
        pho_restaurants.push_back(t);
    }

    map<int,vector<int>> tree;
    int a,b;
    for (int i = 0; i < N-1;i++)
    {
        cin >> a >> b;

        if ((tree.find(a) == tree.end()))
        { // not found
            tree.insert({a,{b}});
        }
        else
        {// found
            tree[a].push_back(b);
        }
        if ((tree.find(b) == tree.end()))
        { // not found
            tree.insert({b,{a}});
        }
        else
        {// found
            tree[b].push_back(a);
        }
    }
    queue<vector<int>> q;
    for (int i = 0; i < M; i++)
    {
        q.push({pho_restaurants[i],0,0});
    }
    set<vector<int>> seen;
    vector<int> temp;
    int current, length;
    long long pho_seen, complete = (pow(10,pho_restaurants.size()) - 1)/9; // integer overflow
    while (!q.empty())
    {
        current=q.front()[0], length=q.front()[1], pho_seen = q.front()[2];
        q.pop();
        temp = {current, pho_seen};
        if (find(seen.begin(),seen.end(),temp) != seen.end())
        {
            continue;
        }
        else
        {
            seen.insert(temp);
        }


        if (find(pho_restaurants.begin(),pho_restaurants.end(),current)!= pho_restaurants.end())
        {
            long num = pow(10,(find(pho_restaurants.begin(), pho_restaurants.end(),current)-pho_restaurants.begin()));
            if ((pho_seen / num)% 10 == 0)
            {
                pho_seen += num;

            }
        }
        cout << current << "|" << length << "|" << pho_seen << endl;
        if (pho_seen == complete)
        {
            cout << length;
            return 0;
        }

        for (int r = 0; r < tree[current].size();r++)
        {
            q.push({tree[current][r], length + 1, pho_seen});
        }
    }
    return 0;
}