Immediate Decodability UVA-644(qsort排序 + 模拟)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char code[1000][100];
bool solve(int p)
{
for(int i = 1; i < p; i++)
{
int len = min(strlen(code[i-1]), strlen(code[i]));
int j;
for(j = 0; j < len; j++)
{
if(code[i-1][j] != code[i][j])
break;
}
if(j == len)
return false;
}
return true;
}
int cmp(void const *va, void const *vb)
{
char *a = (char*)va;
char *b = (char*)vb;
return strcmp(a, b);
}
int main()
{
int d = 0;
while(scanf("%s", code[0]) != EOF)
{
int p = 1;
while(scanf("%s", code[p]) && code[p][0] != '9') { p++;}
qsort(code, p, sizeof(code[0]), cmp); /*这里sizeof内的要注意*/
if(solve(p))
printf("Set %d is immediately decodable\n", ++d);
else
printf("Set %d is not immediately decodable\n", ++d);
}
}
qsort介绍:https://www.runoob.com/cprogramming/c-function-qsort.html
思考:为什么要先排序再查找,不排序为何样例不通过?