POJ-2159 Ancient Cipher

其实这题也不算难,完全没必要用vector、map、pair来做这道题,但是我是想借此题练习一下相关用法。
此题的核心是:统计一个字符串中各个字母出现的频率。比如A出现两次,就记为频率为2

方法一我将用vector、map相关知识来解答
方法二我将用普通数组的方法来解答(26个大写字母减去 ‘A’ 得到的数字可以对应数组下标)

方法一:

知识点:
  1. map默认按照键的大小由小到大来排序,如果要按照值来排序,那么必须要手动实现大小关系的比较
    详细见我的博文:https://blog.csdn.net/wuli_dear_wang/article/details/88562886
  2. pair是map的元素,map实现的是一种关系,一种数据结构,而pair只是单纯数据,类似于int
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <set>
#include <map>
#include <vector>
using namespace std;

bool cmp(const pair<char, int>& a, const pair<char, int>& b) {
	return a.second < b.second;
}    // 定义大小关系

vector<pair<char, int>> judge(string &Plaintext, map<char, int>&totlePla)
{
	for (int i = 0; i < Plaintext.length(); i++)
	{
		if (!totlePla.count(Plaintext[i]))
			totlePla[Plaintext[i]] = 0;
		totlePla[Plaintext[i]]++;
	}
	// 将map中的内容转存到vector中
	vector<pair<char, int>> vec(totlePla.begin(), totlePla.end());
	//对线性的vector进行排序
	sort(vec.begin(), vec.end(), cmp);
	return vec;
}

int main(){
	 
	string Plaintext;
	string ciphertext;
	map<char, int> totlePla;
	map<char, int> totleCip;
	cin >> Plaintext >> ciphertext;
	vector<pair<char, int>> vecPla = judge(Plaintext, totlePla);
	vector<pair<char, int>> vecCip = judge(ciphertext, totleCip);
	if (vecCip.size() != vecPla.size())
	{
		cout << "NO"<<endl;
		return 0;
	}
	for (int i = 0; i < vecPla.size(); i++)
	{
		if (vecCip[i].second != vecPla[i].second)
		{
			cout << "NO" << endl;
			return 0;
		}
	}

	cout << "YES"<<endl;
	return 0;

}

方法二:

知识点:
  1. Sort 函数的第三个参数可以用这样的语句告诉程序你所采用的排序原则
    less<数据类型>()       //从小到大排序
    greater<数据类型>()  //从大到小排序

在这里插入图片描述

  1. 注意sort排序,对于最后的的区间是开区间,左闭右开。所以sort需要指定为 sort(a,a+sizeof(a))
    比如这个题,数组定义为 int a[26];sort(a,a+26)而不是 sort(a,a+25)
#include <iostream>
#include <string>
#include<algorithm>    //因为用了sort()函数  
#include<functional>   //因为用了greater<int>() 
using namespace std;

const int maxn = 26;
int Pla[maxn];
int Cip[maxn];

int main(){
	memset(Pla, 0, sizeof(Pla));
	memset(Cip, 0, sizeof(Cip));
	string Plaintext;
	string Ciphertext;
	cin >> Plaintext >> Ciphertext;
	for (int i = 0; i < Plaintext.size(); i++)
	{
		int num = Plaintext[i] - 'A';
		Pla[num]++;
	}
	for (int i = 0; i < Ciphertext.size(); i++)
	{
		int num = Ciphertext[i] - 'A';
		Cip[num]++;
	}
	sort(Pla, Pla + 26, greater<int>());
	sort(Cip, Cip + 26, greater<int>());
	for (int i = 0; i < 26; i++)
	{
		if (Pla[i] != Cip[i])
		{
			cout << "NO" << endl;
			return 0;
		}
			
	}
	cout << "YES" << endl;
	return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值