Description [title] One day an array of n squares decided to play a game. Initially each equal to the number stored in the lattice grid number (from 1
starts). Each grid to determine their own favorite number di, process each round of game play, any of a lattice grid of i and j meet if | i - j | =
di, you can exchange their digital store. Operation sequence and number of times limitation. You will know each grid favorite number, from 1 to n and an
arrangement. You need to determine whether the game can be arranged to the specified state. [Input format input of the first row contains an integer n-(. 1 <= n-<=
100), indicates the number of grid array. (From the initial state 1-n) comprises a second row of n different integers in size from 1 to n, the arrangement specified. (Final state reached)
a third line contains n integers in size from 1 to n, indicates that the corresponding lattice favorite number. [] If the output format to the specified game can be aligned, output YES, otherwise the output
NO.
The title key is converted meaning of the questions:
a start number at position i is i, the last number in position i is j (pos [j] = i )
If the two numbers can be exchanged, or by several other indirect exchange, that the end state can be achieved.
abs(I-j) = num
(1) I > j : I - j = num , j = I - num
(2) I < j : j - I = num, j = I + num
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
const int maxn = 105;
int n;
int pre[maxn];
int pos[maxn];
int fav[maxn];
void init(){
for(int i=0; i<=n; i++)
pre[i] = i;
}
int find(int x){
int r = x;
while(r!=pre[r])
r = pre[r];
while(x!=r){
int t = pre[x];
pre[x] = r;
x = t;
}
return r;
}
void join(int a,int b){
int fa = find(a);
int fb = find(b);
if(fa!=fb)
pre[fa] = fb;
}
void in_put(){
int t;
for(int i=1; i<=n; i++){
cin >> t;
pos[t] = i; //t最后要在第i的位置——要看能否与i联通起来
}
for(int i=1; i<=n; i++)
cin >> fav[i];
}
void Union(){
//位置i 喜欢的数是fav[i]
for(int i=1; i<=n; i++){
if(i+fav[i]<=n)
join(i,fav[i]+i);
if(i-fav[i]>=1)
join(i,i-fav[i]);
}
}
void check(){
bool flag = 1;
for(int i=1; i<=n; i++){
//这个位置的格子不能与最后在这个位置的格子联通
if(find(i) != find(pos[i])){
flag = 0;
break;
}
}
if(flag)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main(){
while(cin >> n){
init();
in_put();
Union();
check();
}
return 0;
}