找三个“水桶”

  一、 题目要求

     三人行设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。

     如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?(参考核心代码)

     随着论坛的发展,管理员发现水王没有了,但是统计结果表明,有三个发帖很多的ID。据统计他们的发帖数量超过了1/4,你能从发帖列表中快速找到他们吗?

二、设计思路

  三个发帖最多的人每人发的贴都超过了总帖子的1/4,每次减去四个不同的数,他仨发帖数还满足超过1/4。

三、代码

 1 // KingofNavy.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include"iostream"
 6 using namespace std;
 7 
 8 int main()
 9 {
10     int key1=0;
11     int key2=0;
12     int key3=0;
13     int king1;
14     int king2;
15     int king3;
16     int i=0;
17     int array[30]={4,1,2,1,2,2,5,1,4,1,3,3,1,3,4,3,1,2,3,4,1,2,3,2,2,3,1,2,3,1};
18     for(i=0;i<30;i++)
19     {
20         if(key1==0)
21         {
22             king1=array[i];
23             cout<<"Now the King1 of Navy is:"<<array[i]<<endl;
24             key1=1;
25         }
26         else
27         {
28             if(king1==array[i])
29             {
30                 key1++;
31             }
32             else
33             {
34                 if(key2==0)
35                 {
36                     king2=array[i];
37                     cout<<"Now the King2 of Navy is:"<<array[i]<<endl;
38                     key2=1;
39                 }
40                 else
41                 {
42                     if(king2==array[i])
43                     {
44                         key2++;
45                     }
46                     else
47                     {
48                         if(key3==0)
49                         {
50                             king3=array[i];
51                             cout<<"Now the King3 of Navy is:"<<array[i]<<endl;
52                             key3=1;
53                         }
54                         else
55                         {
56                             if(king3==array[i])
57                             {
58                                 key3++;
59                             }
60                             else
61                             {
62                                 key1--;
63                                 key2--;
64                                 key3--;
65                             }
66                         }
67                     }
68                 }
69             }
70         }
71     }
72 
73     cout<<"The ID of King1 of Navy is:"<<king1<<"!"<<endl;
74     cout<<"The ID of King2 of Navy is:"<<king2<<"!"<<endl;
75     cout<<"The ID of King3 of Navy is:"<<king3<<"!"<<endl;
76     cout<<"OVER..."<<endl;
77     return 0;
78 }

四、实现截图

五、总结

从老师近几次的课堂练习我学到这几件事:

1.要进行代码优化

2.善于利用已有的资源,举一反三

 

原文地址:https://www.cnblogs.com/zglsh/p/4463760.html