uva:10602 - Editor Nottoobad(贪心)

本文探讨了一种算法,用于解决在给定一组字符串序列时,如何通过press、copy和delete操作,实现最少的press操作数量。通过将字符串按ASCII码排序,利用后续字符串与前一字符串的相似度进行优化。

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

题目:10602 - Editor Nottoobad


题目大意:有一个机子它由press的动作还有copy和delete字符的动作。给一组字符串,问要输入这样的一组字符串,最少要执行的press动作。


解题思路:将这一组字符串按照ascall码排序后,这样前后两个字符串的相似度是比较高的。然后后一个字符串和前一个字符串相比,看有多少相同的可以copy,就只要统计一下不相同的字符个数。这题比较迷惑人的是题目一直说要求第一个字符串一定要先执行press动作,但是输出却可以任意给一种,不一定是要第一个字符串在第一个位置的那种情况。


代码:

#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;

const int N = 105;
//char first[N];
struct WORDS{

	char str[N];
}words[N];

int cmp (const WORDS & w1, const WORDS & w2) {

	return strcmp(w1.str, w2.str) < 0 ? true :false;
}

int caculate (int n) {
	
	int sum = 0;
	int len;
	int k;
	for (int i = 1; i < n; i++) {

		len = strlen(words[i].str);
		k = 0;
		while (words[i - 1].str[k]  && words[i - 1].str[k] == words[i].str[k]) {

			k++;
		}
		sum += len - k;
	}
	return sum + strlen (words[0].str);
}


int main () {

	int t;
	scanf ("%d", &t);
	while (t--) {

		int n;
		scanf ("%d", &n);
		for (int i = 0; i < n; i++)
			scanf ("%s", words[i].str);
		//memcpy (first, words[0].str, sizeof (first));
		sort (words, words + n, cmp);
		printf ("%d\n", caculate(n));	
		for (int i = 0; i < n; i++)
			printf("%s\n", words[i].str);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值