Title: Three people to design 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?
Problem-solving ideas: According to the discussion in class, the design should be the time complexity O (n). The elimination method to solve the problem: The next two ID if the difference is eliminated, stay in the final must be water King ID (title "More than half of the number of posts" is very important). The ID account given in the program is assumed to be 10
#include <iostream.h>int main () { int a[10]; cout<< "Please enter 10 ID accounts:" <<endl; for (int k=0;k<10;k++) { cin>>a[k]; } int temp=a[0]; int j=1; for (int i=1;i<10;i++) { if (a[i]==a[0]) j + +; else j--; if (j==0) { temp=a[i+1]; j=1; } } cout<< "Water King's account ID:" <<temp<<endl; return 0;}
The results of the program run as follows:
Thinking Summary:
In class in the teacher's classmate's tips think of using the elimination method to solve the problem of water King, immediately feel the world is wonderful. But the method thought, the processing circulation question has appeared, after Hesheyu consultation, the problem has been solved. This exercise also improved my C language programming ability, but also exercise my thinking logic ability. So, later on these small problems should be a lot of practice, improve their IQ and also linked to the programming ability.
Class practice-Finding water king