strchr函数的用法和暴力枚举法的应用
1.
strchr函数能准确的定位某字符在字符串中首次出现的位置,这个函数能解决很多问题,例如:要求输出某字符以后的字符串内容。
其用法如下例:
#include<iostream> #include<cstdio> #include<cstring> //声明
int main() { char string[15]; char *ptr, c = 'r'; strcpy(string, "This is a string"); ptr = strchr(string, c); //用法
if (ptr) printf("The character %c is at position: %d\n", c, ptr-string); //输出
else printf("The character was not found\n"); return 0; }
最后的输出结果为‘r’在字符串中首次出现的位置-1。
2.
暴力枚举的应用
暴力枚举又称蛮力法,就是把所有的可能列举出来,让电脑去计算,从中找出要求的解。其具体步骤为:第一,先找出枚举的范围,将各变量的可能值一一列举出来;第二,分析问题的解需要满足的条件,并用逻辑表达式表示,以筛选出问题的解。
下面有一个经典题目:假币问题
# include <stdio.h>
# include <string.h>
char left[3][7],right[3][7],result[3][5];
int Light(char c)
{
int i;
for(i=0;i<3;i++)
{
switch(result[i][0])
{
case 'e':
if(strchr(right[i],c) != NULL || strchr(left[i],c)!=NULL)
return 0;
break;
case 'u':
if(strchr(right[i],c)==NULL)
return 0;
break;
case 'd':
if(strchr(left[i],c)==NULL)
return 0;
break;
}
}
return 1;
}
int Heavy(char c)
{
int i;
for(i=0;i<3;i++)
{
switch(result[i][0])
{
case 'e':
if(strchr(right[i],c)!=NULL||strchr(left[i],c)!=NULL)
return 0;
break;
case 'u':
if(strchr(left[i],c)==NULL)
return 0;
break;
case 'd':
if(strchr(right[i],c)==NULL)
return 0;
break;
}
}
return 1;
}
int main()
{
int n,i;
char c;
scanf("%d",&n);
while(n>0)
{
for(i=0;i<3;i++)
{
scanf("%s %s %s", left[i],right[i],result[i]);
}
for(c='A';c<='L';c++) //枚举出所有可能
{
if(Light(c))
{
printf("%c is the counterfeit coin and it is light.\n",c);
break;
}
if(Heavy(c))
{
printf("%c is the counterfeit coin and it is heavy.\n",c);
break;
}
}
n--;
}
return 0;
}
本题目用一个for循环列出了所有的可能,并用light和heayy两个函数对可能解进行了筛选,最后找出假币。
蛮力法的优点是节省思考的时间,得出正确的结果的可能性大,并且在后面的动态规划中能用到;其缺点在于算法不够精简,在比赛时可能会超时。
在比赛时,蛮力法可作为检验结果正确与否的工具,提高题目的正答率。
浙公网安备 33010602011771号