题目:
http://poj.org/problem?id=3617
题意:
给出一个n,然后一个长度为n的字符串,每次从这个字符串的首部或者尾部取一个字符构建一个新的字符串,使新字符串的字典序最小
思路:
每次取首部或者尾部字典序较小的那个字符,若相等,则两者同时向中间延伸,比较延伸过程中字符的字典序,仍取延伸过程中字典序较小的那个
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 10010, INF = 0x3f3f3f3f;
int main()
{
char str[N], res[N];
int n;
while(~ scanf("%d", &n))
{
for(int i = 0; i < n; i++) scanf(" %c", &str[i]);
int st = 0, en = n - 1;
for(int i = 0; i < n; i++)
{
bool flag = false;
for(int j = 0; st + j < en - j; j++)
if(str[st+j] != str[en-j])
{
if(str[st+j] < str[en-j]) res[i] = str[st], st++;
else res[i] = str[en], en--;
flag = true;
break;
}
if(!flag) res[i] = str[st], st++;
}
for(int i = 0; i < n; i++)
{
printf("%c", res[i]);
if((i + 1) % 80 == 0) printf("\n");
}
}
return 0;
}
本文介绍了一种算法,用于解决从给定字符串中通过特定规则构造出字典序最小的新字符串的问题。该算法通过比较字符串两端的字符,并选择字典序较小的一端进行构建。

623

被折叠的 条评论
为什么被折叠?



