kmp
#include<bits/stdc++.h> using namespace std; const int maxn=2*1e5+10; int s[maxn],t[maxn]; int s1[2*maxn],t1[maxn]; int Next[maxn]; int n; void get_Next() {//Next数组保存了以i结尾的字符串的最长公共前缀和后缀的起始坐标 int i,j; Next[0] = j = -1; i = 0; while(i < n) { while(j!=-1&&t1[j]!=t1[i])//自身和自身进行匹配 j = Next[j]; Next[++i] = ++j; } } int kmp() { int i,j; i = j = 0; int l1=2*n; int l2=n; while(i < l1&&j<l2) { if(j==-1||s1[i]==t1[j]) { i++;j++; } else j=Next[j]; } if(j == l2) return 1;//存在完全匹配状况 return 0;//不存在匹配情况 } int main() { //freopen("in.txt", "r", stdin); ios::sync_with_stdio(false); cin >> n; for (int i = 0; i < n; i++) cin >> s[i]; for(int i=0; i<n; i++) cin>>t[i]; sort(s, s + n); sort(t, t + n); for (int i = 1; i < n; i++) { s1[i - 1] = s[i] - s[i - 1]; } for (int i = 1; i < n; i++) { t1[i - 1] = t[i] - t[i - 1]; } s1[n - 1] = 360000 + s[0] - s[n - 1]; t1[n - 1] = 360000 + t[0] - t[n - 1]; for (int i = 0; i < n; i++) s1[i + n] = s1[i]; get_Next(); bool flag =kmp(); if (flag) cout << "possible" << endl; else cout << "impossible" << endl; return 0; }