Loading

AtCoder Beginner Contest 277 E Crystal Switches

Crystal Switches

分层图 + \(01bfs\)

按钮的操作就是走分层图的边

因此就构建两张图,然后将特殊点加一个双向边

\(01bfs\) 跑一下就行

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
#include <ctime>
#include <cstdlib>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;

int main()
{
    int n, m, k;
    cin >> n >> m >> k;
    vector<vector<int>>gra(n * 2 + 2);
    vector<int>vis(n * 2 + 2, 0);
    for(int i=0; i<m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        if(c)
        {
            gra[a].push_back(b);
            gra[b].push_back(a);
        }
        else
        {
            gra[a + n].push_back(b + n);
            gra[b + n].push_back(a + n);
        }
    }
    for(int i=0; i<k; i++)
    {
        int x;
        cin >> x;
        gra[x].push_back(x + n);
        gra[x + n].push_back(x);
    }
    deque<array<int, 2>>q;
    q.push_back({1, 0});
    int ans = -1;
    while(q.size())
    {
        auto [now, val] = q.front();
        q.pop_front();
        if(vis[now]) continue;
        vis[now] = 1;
        if(now == n || now == n * 2)
        {
            ans = val;
            break;
        }
        for(int nex : gra[now])
        {
            if(vis[nex]) continue;
            if(abs(nex - now) == n) q.push_front({nex, val});
            else q.push_back({nex, val + 1});
        }
    }
    cout << ans << endl;
    return 0;
}
posted @ 2022-11-12 23:51  dgsvygd  阅读(116)  评论(0编辑  收藏  举报