https://codeforces.com/contest/1316/problem/B
简单的规律 + 字符串的赋值处理
普通遍历赋值超时!!!
得用字符串的 substr 提取子串直接赋值 和 reverse 翻转!!
所以下一次处理字符串的时候一定要注意!!!
一开始的超时代码
#include <iostream>
#include <cstdio>
using namespace std;
int read()
{
int x = 0, w = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-') w = -1;
ch = getchar();
}
while(ch <= '9' && ch >= '0')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * w;
}
int main()
{
int t = read();
while(t--)
{
int n = read();
string str, minn;
int mini;
cin >> str;
for(int k = 1; k <= n; k++)
{
string now = "";
for(int i = k; i <= n; i++)
{
now = now + str[i - 1];
}
if(k == 1)
{
minn = now;
mini = 1;
continue;
}
if((k + n) % 2 == 0)
{
for(int i = k - 1; i >= 1; i--)
{
now = now + str[i - 1];
}
}
else
{
for(int i = 1; i <= k - 1; i++)
{
now = now + str[i - 1];
}
}
if(minn > now)
{
minn = now;
mini = k;
}
}
cout << minn << endl;
cout << mini << endl;
}
return 0;
}
题解代码:
#include <bits/stdc++.h>
using namespace std;
string modified(string& s, int n, int k) {
string result_prefix = s.substr(k - 1, n - k + 1);
string result_suffix = s.substr(0, k - 1);
if (n % 2 == k % 2)
reverse(result_suffix.begin(), result_suffix.end());
return result_prefix + result_suffix;
}
int main () {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
string s, best_s, temp;
int t, n, best_k;
cin >> t;
while (t--) {
cin >> n >> s;
best_s = modified(s, n, 1);
best_k = 1;
for (int k = 2; k <= n; ++k) {
temp = modified(s, n, k);
if (temp < best_s) {
best_s = temp;
best_k = k;
}
}
cout << best_s << '\n' << best_k << '\n';
}
return 0;
}
自己用的:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int read()
{
int x = 0, w = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-') w = -1;
ch = getchar();
}
while(ch <= '9' && ch >= '0')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * w;
}
int main()
{
int t = read();
while(t--)
{
int n = read();
string str, minn;
int mini;
cin >> str;
for(int k = 1; k <= n; k++)
{
string pre = str.substr(k - 1, n);
if(k == 1)
{
minn = pre;
mini = 1;
continue;
}
string suf = str.substr(0, k - 1);
if((k + n) % 2 == 0)
{
reverse(suf.begin(), suf.end());
}
string now = pre + suf;
if(minn > now)
{
minn = now;
mini = k;
}
}
cout << minn << endl;
cout << mini << endl;
}
return 0;
}