2020.3.6 div2 B

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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值