Problem:
• Three people have designed a irrigation forum. Information college students like to exchange irrigation above, legend in the forum there is a "water king", he not only likes to post, but also reply to other ID issued by each post. The "Water King" has been rumored to have posted more than half the number of posts. • If you have a list of posts (including replies) for the current forum, and the ID of the author of the Post is in it, can you quickly find the legendary water king? Thinking of solving problems:The problem can be reduced to: in the STR array, there are 0-9 numbers, one of which exceeds 50%, to find this number.
Design ideas:1, first build a number of arrays, where the water king number more than 50%. 2, the adjacent numbers match, the same is left, the difference is deleted. 3, Traverse once can find water king number.
#include <iostream>#include<ctime>#include<string>using namespacestd;voidMain () {srand (unsigned) time (0)); stringstr =""; intNumstr = +;//Define Array Length intnum=0;//Record Water King number intShuiwang=rand ()%Ten;//randomly define water king numbers while(numstr!=0) { if(rand ()%Ten<=5)//Add Water King number{str+=shuiwang+ -; Num++; } Else //Otherwise, add water king or other numbers{str+=rand ()%Ten+ -; } numstr--; } cout<<"the array of water-containing kings is:"<<str<<Endl; cout<<"the number of water Kings is:"<<num<<Endl; //The adjacent number matches the same copy to the STR1 stringSTR1 =""; for(intI=0; I<str.length (); i=i+2) { if(str[i]==str[i+1]) {str1+=Str[i]; }} cout<<str1<<endl;//at this time, most of the str1 are water king numbers while(1) { intA=rand ()%str1.length (); intB=rand ()%str1.length (); intC=rand ()%str1.length (); if(str1[a]==str1[b]&&str1[a]==Str1[c]) {cout<<"The Water king is:"<<str1[a]<<Endl; Break; } }}
The results of the operation are as follows:
Follow-up practice--Find the Water King 1