E. Nearest Opposite Parity(多源最短路bfs)

简介: E. Nearest Opposite Parity(多源最短路bfs)

题目

题意

思路

  • 多源最短路

代码

scss

复制代码

const int N = 2e5+10;
int a[N];
vector<int> edge[N];
int dist[N];
int ans[N];
void bfs(vector<int> &st,vector<int> &ed)
{
    queue<int> q;
    memset(dist,0x3f,sizeof dist);
    for(auto x:st)
    {
        q.push(x);
        dist[x] = 0;
    }
    while(q.size())
    {
        int u = q.front();q.pop();
        for(auto v:edge[u])
        {
            if(dist[v] != INF)continue;
            dist[v] = dist[u] + 1;
            q.push(v);
        }
    }
    for(auto x:ed)
    {
        if(dist[x] == INF)ans[x] = -1;
        else ans[x] = dist[x];
    }
}
void solve() 
{
    int n;cin >> n;
    vector<int> odd,even;
    
    for(int i = 1;i <= n;i ++)
    {
        cin >> a[i];
        int l = i - a[i],r = i + a[i];
        if(l >= 1)edge[l].push_back(i);
        if(r <= n)edge[r].push_back(i);
        if(a[i]&1)odd.push_back(i);
        else even.push_back(i);
    }
    bfs(odd,even);
    bfs(even,odd);
    for(int i = 1;i <= n;i ++)cout << ans[i] << " ";
}
signed main()
{
    // ios::sync_with_stdio(false);
    // cin.tie(0);
    // cout.tie(0);
    // caseT
    solve();
    
    return 0;
}
/*
*/


相关文章
10 bfs(flood fill与最短路模型)
10 bfs(flood fill与最短路模型)
63 0
CF1272 E.Nearest Opposite Parity(反向建图+BFS)
CF1272 E.Nearest Opposite Parity(反向建图+BFS)
116 0
CF1272 E.Nearest Opposite Parity(反向建图+BFS)
|
机器学习/深度学习 算法 程序员
【算法合集】深搜广搜Prim与Kruskal
广度优先搜索(BFS)又叫广搜,它像一个有远见的人,它是一层一层来实现搜索的,也挺像下楼梯的。 思路: 1.先初始化队列 q; 2.从起点开始访问,并且改变他的状态为已经访问; 3.如果他的队列非空,取出首个元素,将它弹出! 4.如果u == 目标状态,然后对所以与 u 邻近的点进入队列; 5.标记它已经被访问!...............
184 1
SWERC 2020 C. Safe Distance (二分 并查集)
SWERC 2020 C. Safe Distance (二分 并查集)
111 0
UPC Graph (最小生成树 || 并查集+二分)
UPC Graph (最小生成树 || 并查集+二分)
96 0
|
人工智能
Nearest Opposite Parity最短路径+超级源点
time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard output You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i−ai (if 1≤i−ai) or to the position i+ai (if i+ai≤n).
153 0
Nearest Opposite Parity最短路径+超级源点
[Nowcoder] network | Tarjan 边双连通分量 | 缩点 | LCA倍增优化 | 并查集
题目描述 A network administrator manages a large network. The network consists of N computers and M links between pairs of computers. Any pair of computers are connected directly or indirectly by successive links, so data can be transformed between any two computers.
127 0
[Nowcoder] network | Tarjan 边双连通分量 | 缩点 | LCA倍增优化 | 并查集
POJ-1475,Pushing Boxes(双BFS)
POJ-1475,Pushing Boxes(双BFS)
【HDU】1175 连连看(BFS + 剪枝)
【HDU】1175 连连看(BFS + 剪枝)
269 0
【HDU】1175 连连看(BFS + 剪枝)
|
人工智能 BI
[UVA 1599] Ideal Path | 细节最短路
Description New labyrinth attraction is open in New Lostland amusement park. The labyrinth consists of n rooms connected by m passages. Each passage is colored into some color ci .
208 0