题意:
给出一个数组 A=(A0,A1,...,AN−1)A=(A_0,A_1,...,A_{N-1})A=(A0,A1,...,AN−1),进行 KKK 次循环。每次循环,将数组 AAA 中的数字加入到结果数组中。如果加入的数字之前出现过,则将两者之间的数字全部清空,否则将该数字加入到结果数组中。(1≤N≤2∗105,1≤K≤1012,1≤Ai≤2∗105)(1\leq N\leq 2*10^5,1\leq K\leq 10^{12},1\leq A_i\leq 2*10^5)(1≤N≤2∗105,1≤K≤1012,1≤Ai≤2∗105)
思路:
最多NNN次循环之后,一定会出现循环节。我们可以这样进行证明,对于结果数组中的第一个数字,该数字一定对应于数组 AAA 中的一个位置,如果该位置出现了两次,则一定出现了循环节。
而每次循环的过程中,结果数组的第一个数字的位置一定会发生变化。因此我们只需要不断维护结果数组的第一个数字,当找到循环节之后直接计算 K%循环节K\%循环节K%循环节 的结果。
对于原数组中的每个位置,维护该数字到下一个相同数字之间的距离,以及下一个相同数字的位置,然后直接模拟求出循环节即可。
代码:
#include <bits/stdc++.h>
#define __ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define rep(i,a,b) for(int i = a; i <= b; i++)
#define LOG1(x1,x2) cout << x1 << ": " << x2 << endl;
#define LOG2(x1,x2,y1,y2) cout << x1 << ": " << x2 << " , " << y1 << ": " << y2 << endl;
#define LOG3(x1,x2,y1,y2,z1,z2) cout << x1 << ": " << x2 << " , " << y1 << ": " << y2 << " , " << z1 << ": " << z2 << endl;
typedef long long ll;
typedef double db;
const int N = 2*1e5+100;
const int M = 1e5+100;
const db EPS = 1e-9;
using namespace std;
ll n,k,a[N],vis[N],cnt,pos;
//vis[i]: 位置i第一次出现在队首的位置
pair<ll,ll> mp[N]; //记录每一个pos的下一个pos, 以及中间跨越的步数
vector<ll> v[N],ans;
int main()
{
scanf("%lld%lld",&n,&k);
memset(vis,-1,sizeof vis);
rep(i,0,n-1){
scanf("%lld",&a[i]);
v[a[i]].push_back(i);
}
rep(i,1,((int)2*1e5)){
if(!v[i].size()) continue;
int len = v[i].size();
rep(j,0,len-1){
if(j != len-1){
mp[v[i][j]].first = (v[i][j+1]+1)%n;
mp[v[i][j]].second = v[i][j+1]+1-v[i][j];
}
else{
mp[v[i][j]].first = (v[i][0]+1)%n;
mp[v[i][j]].second = n-v[i][j]+v[i][0]+1;
}
}
}
cnt = 0; pos = 0;
ll total = n*k-1ll;
while(cnt+mp[pos].second <= total){
// LOG1("cnt",cnt);
if(vis[pos] != -1){
ll K = cnt-vis[pos];
ll hp = (n*k-vis[pos])%K;
if(hp == 1ll){
printf("\n");
return 0;
}
if(hp == 0) hp = K-1ll;
else hp--;
total = vis[pos]+hp;
cnt = vis[pos];
// LOG1("vis[pos]",vis[pos])
// LOG3("K",K,"hp",hp,"total",total);
break;
}
else vis[pos] = cnt;
cnt += mp[pos].second;
pos = mp[pos].first;
}
// LOG1("total",total);
if(total == cnt+mp[pos].second-1ll){
printf("\n");
return 0;
}
while(cnt <= total){
while(cnt+mp[pos].second <= total){
cnt += mp[pos].second;
pos = mp[pos].first;
}
if(cnt+mp[pos].second-1ll == total) break;
else{
ans.push_back(a[pos]);
pos = (pos+1ll)%n;
cnt++;
}
}
int len = ans.size();
// LOG1("len",len);
if(len == 0) printf("\n");
else{
rep(i,0,len-1){
printf("%lld",ans[i]);
if(i != len-1) printf(" ");
else printf("\n");
}
}
return 0;
}