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;
}
/*
*/


相关文章
|
算法
1091 zoj Knight Moves的BFS算法和DFS
1091 zoj Knight Moves的BFS算法和DFS
60 0
10 bfs(flood fill与最短路模型)
10 bfs(flood fill与最短路模型)
58 0
|
C++
【PAT甲级 - C++题解】1046 Shortest Distance
【PAT甲级 - C++题解】1046 Shortest Distance
65 0
CF1272 E.Nearest Opposite Parity(反向建图+BFS)
CF1272 E.Nearest Opposite Parity(反向建图+BFS)
106 0
CF1272 E.Nearest Opposite Parity(反向建图+BFS)
UPC Graph (最小生成树 || 并查集+二分)
UPC Graph (最小生成树 || 并查集+二分)
93 0
luoguP2205 [USACO13JAN]Painting the Fence S(差分 扫描线思想)
luoguP2205 [USACO13JAN]Painting the Fence S(差分 扫描线思想)
59 0
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
125 0
|
算法
图论最短路及生成树(Prim,Djikstra,Spfa,Bellan-ford,kruskal,topsort)
图论最短路及生成树(Prim,Djikstra,Spfa,Bellan-ford,kruskal,topsort)
140 1
|
人工智能
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).
148 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.
122 0
[Nowcoder] network | Tarjan 边双连通分量 | 缩点 | LCA倍增优化 | 并查集