http://acm.hdu.edu.cn/showproblem.php?pid=1880
1.下面是二分查找(ac)代码:
#include
#include
#include
#define max 100005
typedef struct Node
{
char mo[25];
char yu[85];
}Node;
Node mag1[max];
Node mag2[max];
int cmp1(const void *a,const void *b)
{
Node *c=(Node *)a;
Node *d=(Node *)b;
return strcmp(c->mo,d->mo);
}
int cmp2(const void *a,const void *b)
{
Node *c=(Node *)a;
Node *d=(Node *)b;
return strcmp(c->yu,d->yu);
}
int search(char str[],int len,int tag) //返回查找到的元素在队列中的位置
{
int be=0,en=len-1,t;
while(be<=en)
{
t=(be+en)/2;
if(tag==0)
{
if(strcmp(str,mag1[t].mo)<0)
en=t-1;
else if(strcmp(str,mag1[t].mo)>0)
be=t+1;
else
return t;
}
else
{
if(strcmp(str,mag2[t].yu)<0)
en=t-1;
else if(strcmp(str,mag2[t].yu)>0)
be=t+1;
else
return t;
}
}
return -1;
}
int main()
{
char str[120];
int count=0,f;
int i,len;
while(gets(str))
{
if(strcmp(str,"@END@")==0) break;
for(i=0;i
break;
strncpy(mag1[count].mo,str,i+1);
strcpy(mag1[count].yu,str+i+2);
strcpy(mag2[count].mo,mag1[count].mo);
strcpy(mag2[count].yu,mag1[count].yu);
count++;
}
qsort(mag1,count,sizeof(Node),cmp1);
qsort(mag2,count,sizeof(Node),cmp2);
int n;
scanf("%d",&n);
getchar();
for(i=0;i
gets(str);
if(str[0]=='[')
{
f=search(str,count,0);
if(f>=0)
printf("%s/n",mag1[f].yu);
else
printf("what?/n");
}
else
{
f=search(str,count,1);
len=strlen(mag2[f].mo);
mag2[f].mo[len-1]='/0';
if(f>=0)
printf("%s/n",mag2[f].mo+1);
else
printf("what?/n");
}
}
return 0;
}
2.下面是采用STL map方法代码,不过在杭电acm上会发生memory limit exceeded,不过还是贴出来看看:
#include
#include
map
map
int main()
{
int tag,len,n;
string str,str1,str2,str3;
map
char ch[120];
while(gets(ch))
{
if(strcmp(ch,"@END@")==0) break;
str=ch;
tag=str.find(']');
len=str.length();
str1=str.substr(0,tag+1);
str2=str.substr(tag+2,len-tag);
str3=str.substr(1,tag-1);
ma1.insert(map
ma2.insert(map
}
scanf("%d",&n);
getchar();
for(int i=0;i
gets(ch);
str=ch;
if(ch[0]=='[')
{
iter=ma1.find(str);
if(iter!=ma1.end())
cout<
cout<<"what?"<
else
{
iter=ma2.find(str);
if(iter!=ma2.end())
cout<
cout<<"what?"<
}
return 0;
}
感受:做题时要看清题目,我是因为没去[和]无法ac郁闷了很长一段时间!!!