ACM幸运字符串——应该算是贪心算法吧

该程序是用C++编写的,用于确定一个由小写字母组成的字符串是否为NearlyLuckyNumber。当字符串中每个字母的位置按升序列出时,如果所有列表中任意相邻数字的绝对差是幸运数,则字符串被认为是幸运的。程序采用了贪心策略来处理字符串中的字符选择。

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

#include <iostream>
using namespace std;
// Nearly Lucky Number
int main()
{
	//如果小于=4,就直接输出
	//如果大于4,
	// 
	// 
	//这应该叫贪心?
	int n; cin >> n;
	if (n <= 4) {
		for (int i = 0; i < n; i++) cout << (char) ('a' + i);
		return 0;
	}
	char* c = new char[n] ;
	int j = 0;
	for (int i = 0; i < n; i++) {
		if (i - 4 >= 0 && i - 7 >= 0) {
			if (c[i - 4] < c[i - 7] && c[i - 1] != c[i - 4]) c[i] = c[i - 4];//i-4小,与i-1不相同
			else if (c[i - 7] < c[i-4]&& c[i - 7] != c[i - 3]) { c[i] = c[i - 7]; }//i-7小, i-7与i-3不相同
			else if (c[i - 4] != c[i - 1]) c[i] = c[i - 4];//i-4大,但可以
			else if (c[i - 7] != c[i - 3]) c[i] = c[i - 7];//i-7大,但可以
		}
		else if (i - 4 >= 0 && i - 7 < 0) c[i] = c[i - 4];
		else {
			c[i] =(char) ( 'a' + j);
			j++;
		}
	}
	for (int i = 0; i < n; i++) cout << c[i];
	return 0;
}

Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值