2019年北理复试上机题

1、碎片字符串

形如aabbaaacaa的字符串,可分为五个相同连续字母组成的碎片:'aa','bb','aaa','c','aa',其中每个碎片只出现一次,即该字符串包含'aa','bb','aaa','c'四个碎片,且输出时按字典序排序。

样例:

        输入:a                       输出:a

        输入:aabbaaacaa  输出:aa

                                                        aaa

                                                        bb

                                                        c

代码:

#include<bits/stdc++.h>
using namespace std;

int main(){
	string str;
	cin>>str;
	set<string> s;
	for(int i = 0;i < str.length();i++){
		string temp = "";
		temp += str[i];
		while(str[i] == str[i + 1]){
			temp += str[i++];
		}
		s.insert(temp);
	}
	for(set<string>::iterator iter = s.begin();iter != s.end();iter++){
		cout<<*iter<<endl;
	}
} 

2、哈夫曼树

输入n,以及n个数(用,隔开),构造哈夫曼树(不用真的用树来写代码),输出其最小带权路径长度

eg:输入 4

              2,4,5,7

      输出:35

      输入:4

                 1,1,1,1

       输出:8

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n, sum = 0;
	string str;
	cin>>n>>str;
	vector<int> vect;       //存储数字
	
	//处理字符串,提取数字放入vect 
	char *t = (char *)str.data();
	char *temp = strtok(t, ",");
	while(temp != NULL){
		int i = atoi(temp);
		vect.push_back(i);
		temp = strtok(NULL, ",");
	} 
	
	//主要思想:哈夫曼树的带权路径和=非叶子结点的和
	//每次排序后, vect[i + 1] += vect[i]; vect[i + 1]中存储着这一非叶子结点的路径,并在下次排序时剔除了vect[i] 
	for(int i = 0;i < n - 1;i++){
		sort(vect.begin() + i, vect.end());
		vect[i + 1] += vect[i];
		sum += vect[i + 1];
	}
	cout<<sum;
}

经大佬提醒,使用优先级队列(自动排序)

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n, sum = 0;
	string str;
	cin>>n>>str;
	priority_queue<int, vector<int>, greater<int> >q;       //优先级队列存储数字
	
	//处理字符串,提取数字放入q
	char *t = (char *)str.data();
	char *temp = strtok(t, ",");
	while(temp != NULL){
		int i = atoi(temp);
		q.push(i);
		temp = strtok(NULL, ",");
	} 
	
	//主要思想:哈夫曼树的带权路径和=非叶子结点的和
	//出队最小的两个值,加和入队,同时加入sum 
	for(int i = 0;i < n - 1;i++){
		int a = q.top();q.pop();
		int b = q.top();q.pop();
		q.push(a + b);
		sum += a + b;
	}
	cout<<sum;
}

 

  • 12
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值