链接:

https://codeforces.com/contest/1272/problem/E

题意:

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).

For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that aj has the opposite parity from ai (i.e. if ai is odd then aj has to be even and vice versa).

思路:

写了好久DFS发现有环不能处理。。看了大佬博客才懂。

考虑从a开始的最短路,计算的是a到x的最短路。

反向建图,跑出来的最短路,就是他能到达的点往自己的最短路。

建立两个新点,分别连奇数点和偶数点,跑最短路。

代码:

#include<bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int MAXN = 2e5+10; vector<int> G[MAXN];
int a[MAXN], ans[MAXN], dis[MAXN], vis[MAXN];
int n; void SPFA(int s)
{
queue<int> que;
for (int i = 1;i <= n+2;i++)
dis[i] = INF, vis[i] = 0;
que.push(s);
dis[s] = 0;
vis[s] = 1;
while(!que.empty())
{
int u = que.front();
que.pop();
vis[u] = 0;
for (int i = 0;i < (int)G[u].size();++i)
{
int node = G[u][i];
if (dis[node] > dis[u]+1)
{
dis[node] = dis[u]+1;
if (vis[node] == 0)
{
que.push(node);
vis[node] = 1;
}
}
}
}
} int main()
{
cin >> n;
for (int i = 1;i <= n;++i)
cin >> a[i];
for (int i = 1;i <= n;++i)
{
if (i-a[i] >= 1)
G[i-a[i]].push_back(i);
if (i+a[i] <= n)
G[i+a[i]].push_back(i);
}
for (int i = 1;i <= n;++i)
{
if (a[i]%2 == 1)
G[n+1].push_back(i);
else
G[n+2].push_back(i);
}
SPFA(n+1);
for (int i = 1;i <= n;++i)
if (a[i]%2 == 0) ans[i] = dis[i];
SPFA(n+2);
for (int i = 1;i <= n;++i)
if (a[i]%2 == 1) ans[i] = dis[i];
for (int i = 1;i <= n;++i)
cout << ((ans[i] == INF) ? -1 : ans[i]-1) << ' ' ;
cout << endl; return 0;
}

最新文章

  1. [C1] C1FlexGrid 行列增删&amp;单元格合并拆分
  2. tabbarItem字体及图片颜色设置
  3. M1事后分析汇报总结
  4. 简单几何(圆与多边形公共面积) UVALive 7072 Signal Interference (14广州D)
  5. 暂停和恢复Activity Android
  6. iOS开发——面试笔试精华(三)
  7. Collision使用 获取其组件执行变色操作
  8. COMET技术具体实现 结合PHP和JQUERY
  9. [Python]新手写爬虫全过程(转)
  10. ASP.NET MVC中对Model进行分步验证的解决方法
  11. linux安装配置solr
  12. jq,返回上一页,小记history.back(-1)和history.go(-1)区别
  13. iframe 里的高度适应的问题
  14. Exp3 免杀原理与实践 20164320 王浩
  15. AX_xSession
  16. git关联远程仓库
  17. 资产管理平台 glpi
  18. 在windows下安装git中文版客户端并连接gitlab
  19. [DeploymentService:290066]Error occurred while downloading files from admin server for deployment request &quot;0&quot;. Underlying error is: &quot;null&quot;
  20. _event_spawn

热门文章

  1. 微信公众号开发 token 验证程序
  2. Drools 规则文件语法概述
  3. IDEA远程调试Ambari Server
  4. 学习docker 部署nginx记录
  5. ETC1/DXT1 compressed textures are not supported when publishing to iPhone
  6. linux下测试某网址或IP端口能否访问
  7. java-java技术链接
  8. Flask介绍及简单使用
  9. unittest管理接口用例
  10. Oracle 数据类型比较规则