Chapter IV algorithm contest entry classic study notes 2
As a function of the parameter of the function
Examples 4-1 old password (Ancient Cipher, NEERC 2004, UVa1339)
Given the same length and no more than two strings 100, each of which we can judge whether a letter string rearrangement, and 26 make a letter-one mapping such that the two strings are the same. For example, JWPUDJSTVP can be obtained after rearrangement WJDUPSJPVT, then each letter before it is mapped to a letter (B-> A, C-> B , ..., Z-> Y, A-> Z), to give VICTORIOUS. Two input strings, output YES or NO
Title Analysis:
as can be rearranged letters, each letter position is not important, the number of times each letter appears
① count the number of each letter appears in the two strings, two arrays cnt1 [26], cnt2 [26 ]
our sorting, the same result after sorting after ②, we described two strings entered by rearrangement can become the same one mapping so that the core of the questions in that Sort
the C language library stdlib.h has a function called qsort to achieve a well-known fast sorting algorithm. To understanding
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
/*前3个参数不难理解,分别是待排序的数组起始地址、元素个数和每个元素的大小。最 后一个参数比较特别,是一个指向函数的指针,该函数应当具有这样的形式:int cmp(const void *, const void *) { … }
*/
Constant point "universal" pointer: const void *, which can be converted into any type of mandatory pointer
#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
int cmp(const void* a,const void *b)
{
return *(int*)a-*(int*)b;
//(int*)a:类型转化 变成int类型的指针,然后*这个指针,得到这个变量
}
int main()
{
char s1[105],s2[105];
while(cin>>s1>>s2)
{
int cnt1[26]={0},cnt2={0};
int len=strlen(s1),flag=1;
for(int i=0;i<len;i++)
{
cnt1[s1[i] - 'A']++, cnt2[s2[i] - 'A']++;
}
qsort(cnt1, 26, sizeof(int), cmp);//void qsort(void *base, sieze_t num, size_t size, int(*comparator)(const void* ,const void*) );
qsort(cnt2, 26, sizeof(int), cmp);// 数组名字 数组大小 单位长度 比较函数
for (int i = 0; i < 26; i++)
if (cnt1[i] != cnt2[i]) { flag = 0; break; }
if (flag)printf("YES\n");
else printf("NO\n");
}
return 0;
}