STDOJ 真简单题 & Codeforces Round #605 (Div. 3) E. Nearest Opposite Parity(反向建图 + 最短路)

5 篇文章 0 订阅
4 篇文章 1 订阅

链接 E. Nearest Opposite Parity

题目

在这里插入图片描述

思路

正向建图,每个点跑一遍 b f s bfs bfs 会超时;

反向建图,然后找到一次就可以满足题意的点作为起始点,然后由起始点继续拓展即可;

AC代码

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <map>
#include <vector>
#include <string>
#include <queue>

#define x first
#define y second

using namespace std;

const double eps = 1e-12;
const int N = 200010, P = 13331;
const int mod = 100003;
typedef pair<double, double> PDD;
typedef long long ll;
typedef unsigned long long ull;
const double pi = acos(-1);

int n;
int a[N];
int ans[N];
queue<int> q;
vector<int> v[N];

int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
		if (i - a[i] >= 1) v[i - a[i]].push_back(i);
		if (i + a[i] <= n) v[i + a[i]].push_back(i);
	}
	for (int i = 1; i <= n; i++) {
		if ((i - a[i] >= 1 && (a[i] & 1) ^ (a[i - a[i]] & 1)) || (i + a[i] <= n && (a[i] & 1) ^ (a[i + a[i]] & 1))) {
			ans[i] = 1;
			q.push(i);
		}
	}
	while (q.size()) {
		int t = q.front();
		q.pop();
		for (int i = 0; i < v[t].size(); i++) {
			if (ans[v[t][i]] == 0) {
				ans[v[t][i]] = ans[t] + 1;
				q.push(v[t][i]);
			}
		}
	}
	for (int i = 1; i <= n; i++) {
		if (ans[i]) cout << ans[i] << " \n"[i == n];
		else cout << -1 << " \n"[i == n];
	}
	
}

——END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半碗无糖蓝莓冻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值