POJ2159 Ancient Cipher

题目很抽象,没有说明按哪种规则Substitution cipher,即A->? ~ Z->?并未说明,没有指明permutation cipher使用的数组,即怎么换序也不知道。

确定的事:字母变换过程虽然未指明,但同一个字母肯定对应同一其他字母;

学习内容:c++的I/O流;STL中的sort 对给定区间所有元素进行排序 ;

#include <iostream> //悲剧的WA
#include <algorithm> //包含一组基础算法:置换、排序、合并、搜索等
using namespace std;

int main()
{
    const int maxlength = 100; //少于100个字母
    char plate[maxlength] = {0};
    char guess[maxlength] = {0};//定义两个字符数组 分别代表两行input
    int freqPlate[26] = {0};
    int freqGuess[26] = {0};//两个数组用来统计字符出现频次

    // 输入两行
    cin.getline(plate,maxlength+1);
    cin.getline(guess,maxlength+1);

    //计算两行长度 不相等直接no ; string 对象才有.length()方法
    int lenPlate = sizeof plate / sizeof plate[0];
    int lenGuess = sizeof guess / sizeof guess[0];

    if (lenPlate != lenGuess)
    {
        cout << "NO" ;
    }
    else // 循环统计字母频次
    {
        for (int i=0;i<lenPlate;i++)
        {
            freqPlate[plate[i] - 'A']++;
            freqGuess[guess[i] - 'A']++;
        }
        sort(freqPlate,freqPlate+26);
        sort(freqGuess,freqGuess+26);
        
        int flag = 1;
        for (int j=0;j<26;j++)
        {
            if (freqPlate[j] != freqGuess[j])
            {
                flag = 0;
                break;
            }
        }
        (flag==1)?(cout<<"YES"):(cout<<"NO");
    }
    return 0;
}

 稍微改动后,却正确了。百思不得其解

#include <iostream>
//#include <cstring>
#include <algorithm> //包含一组基础算法:置换、排序、合并、搜索等
using namespace std;

int main()
{
    const int maxlength = 100; //少于100个字母
    char plate[maxlength] = {0};
    char guess[maxlength] = {0};//定义两个字符数组 分别代表两行input
//     int freqPlate[26] = {0};
//     int freqGuess[26] = {0};//两个数组用来统计字符出现频次
    char freqPlate[26],freqGuess[26];
    memset(freqPlate,0,26);
    memset(freqGuess,0,26);
    // 输入两行
//     cin.getline(plate,maxlength+1);
//     cin.getline(guess,maxlength+1); //这个输入方法也是可行的
    cin>>plate;
    cin>>guess;//差别在于cin遇到空格就不再输入了,getline可以整行搞定
    //计算两行长度 不相等直接no ; string 对象才有.length()方法
    int lenPlate = sizeof plate / sizeof plate[0];
    int lenGuess = sizeof guess / sizeof guess[0];

    if (lenPlate != lenGuess)
    {
        cout << "NO";
    }
    else // 循环统计字母频次
    {
        for (int i=0;i<lenPlate;i++)
        {
            freqPlate[plate[i] - 'A']++;
            freqGuess[guess[i] - 'A']++;
        }
        sort(freqPlate,freqPlate+26);
        sort(freqGuess,freqGuess+26);
        
        int flag = 1;
        for (int j=0;j<26;j++)
        {
            if (freqPlate[j] != freqGuess[j])
            {
                flag = 0;
                break;
            }
        }
        (flag==1)?(cout<<"YES"):(cout<<"NO");
    }
    return 0;
}

 红色标注的地方,试过

int freqPlate[26],freqGuess[26];
memset(freqPlate,0,26);
memset(freqGuess,0,26);    
char freqPlate[26] = {0};
char freqGuess[26] = {0};

均不可以,原因尚不知。

知:memset是按字节初始化的;

注:int freqGuess[26] = {1};仅仅是把第0个元素置1,其他默认为0.

原文地址:https://www.cnblogs.com/lingc/p/3421319.html