预处理,将26个字符的所属组、耗时 存于两数组 g[26], t[26]。

遍历字符串,和前一字符同组加额外2t耗时(用一个假前驱可免去第一个字符的特判)

#include <iostream>

using namespace std;

string a[] = {
	"abc","def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
};

int t[26], g[26];
int main() {
	// 预处理
	for (int i = 0; i < 8; i++) {
		for (int j = 0; a[i][j]; j++) {  // 遍历到 "\0" 则停止
			int id = a[i][j] - 'a';
			g[id] = i;                   // 组号 0 ~ 8
			t[id] = j + 1;               // 组内各按键耗时
		}
	}

	string s;
	while (cin >> s) {
		int cnt = 0, preg = -1;
		for (auto c : s) {
			int curg = g[c - 'a'];

			if (curg == preg) cnt += 2;  // 同组多耗时 2t
			
			cnt += t[c - 'a'];           // 当前字符耗时

			preg = curg;
		}
		cout << cnt << endl;
	}
}