例题3-6 环状序列(Circular Sequence,ACM/ICPC Seoul 2004,UVa1584)

原题链接:https://vjudge.net/problem/UVA-1584
分类:字符串
备注:水题、取模
思路:按顺序以每个字符为头都比较一次保留最小的即可。
代码如下:

#include<stdio.h>
#include<string.h>
const int maxn = 100 + 5;
int T;
char s[maxn];
int cmp(char* s, int a, int b, int len)
{
	for (int i = 0; i < len; i++)
		if (s[(a + i) % len] > s[(b + i) % len])return 0;
		else if (s[(a + i) % len] < s[(b + i) % len])return 1;
	return 1;
}
int main(void)
{
	scanf("%d", &T);
	while (T--)
	{
		scanf("%s", s);
		int len = strlen(s), ans = 0, temp = 1;
		for (int i = 0; i < len - 1; i++)
		{
			if (!cmp(s, ans, temp, len))ans = temp;
			temp++;
		}
		for (int i = 0; i < len; i++)printf("%c", s[(ans + i) % len]);
		printf("\n");
	}
	return 0;
}
发布了22 篇原创文章 · 获赞 23 · 访问量 515

猜你喜欢

转载自blog.csdn.net/TK_wang_/article/details/104352507