NC217473. 作弊
描述
输入描述
一行字符串,表示需要传达的信息,有可能是文言文拼音,中仅包含小写英文字母。
输出描述
仅一行一个正整数表示问题的答案,表示传达信息所需最少的‘点头’and‘摇头’的次数之和。
示例1
输入:
aaaaaa
输出:
6
说明:
‘a’用'点头'代表即可示例2
输入:
abcabc
输出:
10
说明:
示例3
输入:
havefuninthegame
输出:
54
说明:
解释那么长,这点地方够吗?C++ 解法, 执行用时: 141ms, 内存消耗: 8212K, 提交时间: 2021-07-15 17:50:07
#include<bits/stdc++.h> using namespace std; int main(){ string s; cin>>s; vector<int>a(26,0); for(char t:s)a[t-'a']++; priority_queue<int,vector<int>,greater<int> >q; for(auto t:a)if(t)q.push(t); int ans=0; while(q.size()>1){ int a=q.top(); q.pop(); int b=q.top(); q.pop(); ans+=a+b; q.push(a+b); } cout<<ans; }
pypy3 解法, 执行用时: 767ms, 内存消耗: 43700K, 提交时间: 2021-06-19 11:06:22
import heapq from typing import Counter str = input() dic = list(Counter(str).values()) heap = heapq.heapify(dic) res = 0 while len(dic)>=2: a = heapq.heappop(dic) b = heapq.heappop(dic) res += a + b heapq.heappush(dic, a + b) print(dic[0] if not res else res)
Python3 解法, 执行用时: 347ms, 内存消耗: 13860K, 提交时间: 2021-06-19 11:11:12
import heapq from typing import Counter str = input() dic = list(Counter(str).values()) heap = heapq.heapify(dic) res = 0 while len(dic)>=2: a = heapq.heappop(dic) b = heapq.heappop(dic) res += a + b heapq.heappush(dic, a + b) print(dic[0] if not res else res)