首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于HDU上一道水题求解。小弟我DEBUG快要疯了。求各位进来看看

2012-04-08 
关于HDU上一道水题求解。。。我DEBUG快要疯了。。求各位进来看看http://acm.hdu.edu.cn/showproblem.php?pid10

关于HDU上一道水题求解。。。我DEBUG快要疯了。。求各位进来看看
http://acm.hdu.edu.cn/showproblem.php?pid=1004
题目链接如上,我一开始用的是快排,把字符串按字典序排列,然后方便比较。。但是交上去老WA。。
这个是一开始的代码。。求分析一下BUG在哪里。。
#include<stdio.h>
int cmp(const void*a,const void *b)
{
  return *(char *)a-*(char*)b;
}
char p[1100][20];
main()
{
  int a,b;
  scanf("%d",&a);
  while(a)
  {
  int max=0,s,c=1,t;
  for(b=0;b<a;b++) scanf("%s",p[b]);
  qsort(p,a,sizeof(p[0]),cmp);
  if(a==1) t=0;
  for(s=1;s<a;s++)
  {
  if(!strcmp(p[s-1],p[s])) c++;
  else c=1;
  if(c>max) {max=c; t=s;}
  }
  printf("%s\n",p[t]);
  scanf("%d",&a);
  }
}

后来我用暴力法又写了一个,目前唯一发现的区别就是。如果输入
5
red
red
ka
ka
z
上面的代码输出的是ka,我后来暴力过的程序是red。但是题目里面又有一句这样的话
It is guaranteed that there is a unique solution for each test case.
求各位大牛相助。。。

[解决办法]
我没有看懂楼主的意思,要快排做什么呢??这是我的AC代码。C++写的,仅供参考吧!

C/C++ code
#include <iostream>#include <string>#include <map>using std::string;using std::map;using std::cout;using std::cin;using std::endl;int main(){    int nCount,i,nMax;    string strColor;    map<string,int> ColorSet;    cin>>nCount;    map<string,int>::iterator iterRes;    while(nCount != 0)    {        i = 0;        ColorSet.erase(ColorSet.begin(),ColorSet.end());        while(i<nCount)        {            ++i;            cin>>strColor;            ++ColorSet[strColor];        }        iterRes = ColorSet.begin();        nMax = iterRes->second;        for (map<string,int>::iterator iter = ColorSet.begin();iter != ColorSet.end();iter++)            if (iter->second>nMax)            {                iterRes = iter;                nMax = iter->second;            }        cout<<iterRes->first<<endl;        cin>>nCount;    }    return 0;}
[解决办法]
比较大小的函数定义错了。
你的
int cmp(const void*a,const void *b)
{
return *(char *)a-*(char*)b;
}

应该是
return strcmp ((char *)a, (char *)b); 


[解决办法]
看了半天没看懂LZ的代码,其实这个map容器就行,简单易懂
C/C++ code
#include<iostream>#include<map>#include<string>using namespace std;int main(){    int n;    map<string,int> s;    while(cin>>n && n){        int min=-1;        s.clear(); //清空        string str;        int i;        for(i=0;i<n;i++){            cin>>str;            s[str]++; //直接这么写,map可以直接生成key为str的pair,并且初始为0,++就得1        }        map<string,int>::iterator it,target;//迭代器,其实理解成map的下标就行        for(it=s.begin();it!=s.end();it++){            if(it->second>min){                min=it->second;                target=it;            }        }        cout<<target->first<<endl;    }    return 0;} 

热点排行
Bad Request.