First, the topic
A three-person line designed a forum for irrigation. 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? Second, the design idea of the teacher gave the "consumer music" idea, according to this idea, the ID into an array, from the first start and the following comparison, not the same "eliminate", because the water king's ID appears more than half, so the remaining ID after the elimination of the Water King ID. The way to discuss with classmates in class is to use a variable to count to achieve "elimination". Third, the Code
1#include <iostream.h>2 3 intMain ()4 {5 inta[ -];6 inti,j,k=1;7 intShui;8cout<<"Suppose there are 10 IDs,";9 for(i=0;i<Ten; i++)Ten { Onecout<<"Please enter section"<<i+1<<"an ID:"<<Endl; ACin>>A[i]; - } -shui=a[0]; the for(i=1;i<Ten; i++) - { - if(shui!=A[i]) - { +k=k-1; - if(k<0) + { Ashui=a[i+1]; atk=1; -i++; - } - } - Else - { inShui=A[i]; -k=k+1; to } + } -cout<<"the water King's ID is:"<<shui<<Endl; the return 0; *}
Iv. Results of operation
V. Summary
This question continues to be an optimization problem, and if it is done by traversing the count, it is possible to compare all occurrences of the ID number, but the time complexity is high, not the optimal algorithm. Algorithm optimization has a long way, should think more good method, usually write also should pay attention to look for better algorithm.
The question of finding water king