找水王
要求:
UNIN队设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。
如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?
设计思路:
发帖者的id随机生成动态数组。水王发帖数量最多,最不怕消除,利用这点,消除相邻元素id不同的两个元素,最后剩下的就是“水王”。
实现代码:
//找水王(在一个论坛中,发帖数超过总帖数的一半的那个id号) #include<iostream> #include<string> #define N 10 //可以定义列表长度 using namespace std; int main() { string king; //定义列表 string IdList[N]={"2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员"}; //string IdList[N]={"2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员","2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员"}; //string IdList[N]={"2水货","2水货","3潜水员","2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员","2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员"}; //string IdList[N]={"oottt","eee","ott","oottt","oottt","oottt","oottt","oottt","tt55","oottt"}; //string IdList[N]={"1","2","3","1","1","1","1","2","5","1"}; //假设第一个id是水王 int i=0; int num=1; king=IdList[0]; for(i=1;i<N;i++) { //如果当前id和king id不同 if(IdList[i]!=king) { //num-1 num=num-1; //num为0,将下一个id 设为 king,并直接跳过下一次循环,并将 num设为1 //若num不为0,king 不变 if(num==0) { king=IdList[i+1]; i=i+1; num=1; } } //若id和king id相同,num+1 else { king=IdList[i]; num=num+1; } } cout<<"要找的水王的 id 为:"<<king<<endl; return 0; }
运行结果:
①测试文字列表string IdList[10]={"2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员"};
②测试更长的列表string IdList[30]={"2水货","2水货","3潜水员","2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员","2水货","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","3潜水员","1水王","3潜水员","1水王","1水王","1水王","1水王","2水货","3潜水员"};
③测试数字和普通字符串
string IdList[10]={"oottt","eee","ott","oottt","oottt","oottt","oottt","oottt","tt55","oottt"};
string IdList[10]={"1","2","3","1","1","1","1","2","5","1"};
6、总结分析:
这次的问题比较简单,实现起来不是很难,但方法的好坏决定了这个程序的运算时间和复杂度。