uvalibe4294 Shuffle

本文详细阐述了一种用于寻找序列中重复位置的算法。通过使用标记数组和遍历序列,该算法能够有效识别并标记重复元素。进一步地,通过检查序列的后续部分,算法能确定重复序列的起始位置,从而解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

the main algorithm of the code:

1, find the first repeat position of the sequence, and mark it (for that once it repeat, it can never be ok)

2,use the array named ok to mark whether the sequence from i to i+s-1 is never repeat

3,check from the position i to the end to find that if the ok[i] is always true, which means that the later word is fine(= =), if so , the position of the first word can be sure as the n-i, s0 ans++

code:

#include<iostream>  
#include<cstdio>  
#include<cstring>  
using namespace std;  
  
typedef long long int64;  
  
const int INF = 0x3f3f3f3f;  
const int MAXN = 100010;  
  
int s, n;  
int arr[MAXN];  
int cnt[MAXN];  
bool first[MAXN], ok[MAXN];  

void init() {
	memset(first, 0, sizeof(first));
	memset(ok, 0, sizeof(ok));
	memset(cnt, 0, sizeof(cnt));
	first[0] = 1, ok[n] = 1;
	int i;
	for(i=0; i<s&&i<n&&!cnt[arr[i]]; i++) {
		cnt[arr[i]] = 1;
		first[i+1] = 1;
	}
	if(i==n && i<s && first[i]) {
		while(i++<s) first[i] = 1;
	}
	memset(cnt, 0, sizeof(cnt));
	ok[n] = 1;
	int count = 0;
    for(int i=n-1; i>=0; --i){  
		if(cnt[arr[i]]++ == 0) {
//cnt[arr[i]]++;//it is wrong
			
			count++;
		}

        if(count == s || n-i<s&&n-i==count){  
            ok[i] = true;  
        }  
        if(i+s-1<n){  
            if(--cnt[arr[i+s-1]] == 0){  //the word is out of consider
                --count;  
            }  
        }  
    }  
}

bool check(int st) {
	while(st<n) {
		if(!ok[st]) return false;
		st += s;
	}
	return true;
}

int main() {
	int kase;
	scanf("%d", &kase);
	while(kase--) {
		scanf("%d%d", &s, &n);
		for(int i=0; i<n; i++) {
			scanf("%d",&arr[i]);
		}
		init();
		int ans = 0;
		for(int i=0; i<s; i++) //give out all the possible position
			if(first[i] && check(i)) {
				++ans;
			}
		printf("%d\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值