UVALive 2755 Hidden Password (最小表示法)

本文介绍了一种求解字符串最小字典序表示的高效算法,通过对比字符并调整起始位置,实现O(n)的时间复杂度。适用于竞赛及实际问题解决。

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

题目链接:https://cn.vjudge.net/problem/UVALive-2755

题目大意:求一个字符串的最小字典序表示

思路:参考https://wenku.baidu.com/view/185b95d726fff705cc170a7a.html,复杂度为O(n)


#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define fin freopen("a.txt","r",stdin)
#define fout freopen("a.txt","w",stdout)
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
const int inf = 1e9 + 10;
const int maxnode = 4e5 + 10;
const int sigma_size = 26;
const int maxn = 1e5 + 10;
char s[maxn*2];
int n;

int solve()
{
	int i = 0, j = 1, k = 0;
	while(i < n/2 && j < n/2)
	{
		if(k == n/2) return i;
		if(s[i+k] == s[j+k]) k++;
        else if(s[i+k] < s[j+k]) { j += k+1; k = 0; }
        else
        {
         	i += k+1;
         	
        	if(i > j) swap(i, j);
        	if(i == j) j++;
        	k = 0;
        }
	}
	return i;
}


int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
    	scanf("%d%s", &n, s);
    	for(int i = n; i <= n*2-1; i++)
    		s[i] = s[i-n];
    	n *= 2;
    	printf("%d\n", solve());
    }
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值