思路:
与题目 MT3055 交换排列 类似
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n, fa[N], b[N], d[N];
void init(int n)
{
for (int i = 1; i <= n; i++)
fa[i] = i;
}
int find(int x)
{
return x == fa[x] ? x : (fa[x] = find(fa[x]));
}
void merge(int i, int j)
{
int x = find(i), y = find(j);
if (x != y)
fa[x] = y;
}
int main()
{
cin >> n;
init(n);
for (int i = 1; i <= n; i++)
{
cin >> b[i];
}
for (int i = 1; i <= n; i++)
{
cin >> d[i];
}
for (int i = 1; i <= n; i++)
{
if (i - d[i] >= 1)
merge(i, i - d[i]);
if (i + d[i] <= n)
merge(i, i + d[i]);
}
for (int i = 1; i <= n; i++)
{
if (find(i) != find(b[i]))
{
cout << -1;
return 0;
}
}
cout << 1;
return 0;
}