OJ_键盘输入问题

题干

OJ_键盘输入问题_第1张图片

c语言实现

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
using namespace std;

int main() {
	//记录每个字母需要花费多少时间
	map<char, int> inputTime = {
		{'a',1},{'b',2},{'c',3},
		{'d',1},{'e',2},{'f',3},
		{'g',1},{'h',2},{'i',3},
		{'j',1},{'k',2},{'l',3},
		{'m',1},{'n',2},{'o',3},
		{'p',1},{'q',2},{'r',3},{'s',4},
		{'t',1},{'u',2},{'v',3},
		{'w',1},{'x',2},{'y',3},{'z',1},
	};

	map<char, int> keymap = {
		{'a',2},{'b',2},{'c',2},
		{'d',3},{'e',3},{'f',3},
		{'g',4},{'h',4},{'i',4},
		{'j',5},{'k',5},{'l',5},
		{'m',6},{'n',6},{'o',6},
		{'p',7},{'q',7},{'r',7},{'s',7},
		{'t',8},{'u',8},{'v',8},
		{'w',9},{'x',9},{'y',9},{'z',9},
	};

	char str[200];
	while (scanf("%s", str) != EOF) {
		int lastkey = -1;//上次按下的按键,最开始是没有
		int totaltime = 0;
		for (int i = 0; str[i] != '\0'; ++i) {
			//判断是否要等待
			if (keymap[str[i]] == lastkey) {
				totaltime += 2;
			}
			totaltime += inputTime[str[i]];
			lastkey = keymap[str[i]];
		}
		printf("%d\n", totaltime);
	}

	return 0;
}

你可能感兴趣的:(数据结构与算法,算法,c语言)