First, design ideas
(1) Enter the Post ID record form
(2) Start with the first ID, and follow the post ID to compare, if the same counter plus one, or minus one. If the value of the counter is reduced to zero, the current ID is re-selected to start the record comparison.
(3) Output results
Second, the source code
1 //Shuiwang.cpp:Defines the entry point for the console application.2 //3 4#include"stdafx.h"5#include"iostream.h"6 #defineMAXSIZE 207 8 voidFindwater (intId[],intLenint&water)9 {Ten intCounter=0;//counter One for(intI=0; i<len;i++) A { - if(counter==0)//if the counter is zero - { theWater=id[i];//record the ID of the current post as the water king suspect -counter++; - } - Else + { - if(Water==id[i])//If the water king suspects the same as the following ID +counter++;//The counter is recorded, otherwise minus one A Else atcounter--; - } - } - } - intMainintargcChar*argv[]) - { in intId[maxsize];//Post record form - intnum,waterking;//number of posts, water King tocout<<"Please enter the number of posts:"; +Cin>>num; -cout<<"Please enter the Post ID:"; the for(intI=0; i<num;i++) * { $Cin>>Id[i];Panax Notoginseng } - Findwater (id,num,waterking); thecout<<"The Water king is:"<<WaterKing<<Endl; + return 0; A}
Third, the experiment
Iv. Experience
This program is not difficult, because the most stupid method is relatively simple. But the teacher asked us to optimize the algorithm, requiring a time complexity of O (n), which is a bit difficult. I did not think of how to optimize the beginning, so the teacher suggested that we do subtraction on the Posting record table, to eliminate music. I and the deskmate discussed a kind of adjacent ID to eliminate the algorithm, we tested a few sets of data found to be effective. Just as we were complacent, another classmate proposed a situation where the algorithm could not find the real water king to reorganize the data. I thought for a long time after class, but I couldn't solve it. Finally, I consulted other students, I have his ideas to understand after the program I wrote.
Software engineering with small work--looking for "Water king" (C + +)