课后作业:寻找水王

一、作业题目

      三人行设计了一个灌水论坛,信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子总数目的一半。如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?

二、程序设计思路

     (1)输入论坛帖子的列表

     (2)从第一个开始,比较相邻的两个ID号,相同的话,此ID出现的次数的计数器加1;不同的话,消去进行比较的这两个ID,最后剩下的ID即为水王的ID。

     (3)输出结果

三、源代码

#include<iostream>
using namespace std;

/*
void getArray(int id[])
{
    fstream fstrInfile;
    fstrInfile.open("array.txt", ios::in);

    if (!fstrInfile.is_open())
    {
        cout << "文件未被打开!!" << endl;
        exit(1);
    }
    for (int i = 0; i < 10; i++)
    {
        fstrInfile >> id[i];
        cout << id[i] << " ";
    }
    cout << endl;
    fstrInfile.close();
}*/


int Find(int id[], int n, int &Water_King)
{

    int count = 0, times = 0;            //记录相同的ID的数目
    for (int i = 0; i<n; i++)
    {
        if (count == 0)              
        {
            Water_King = id[i];                   //当前的ID不是水王
            count++;                               
            times = 0;
            times++;
        }
        else                                 
        {
            if (Water_King == id[i])             //当前ID是水王
            {
                count++;                     //计数加1
                times++;
            }

            else
                count--;                     //计数减1
        }
    }
    return times;

}
int main()
{

    int id[100];                  
    int m, Water_King, num;                          //帖子的总数量,水王ID,相同的帖子数目
    cout << "输入帖子数量:" << endl;
    cin >> m;
    cout << "输入帖子ID:" << endl;
    for (int i = 0; i<m; i++)
    {
        cin >> id[i];
    }
    num = Find(id, m, Water_King);
    if (num>(m / 2))                                 //相同ID数目大于总数一半,才判断为水王
        cout << "水王是:" << Water_King << endl;
    else
        cout << "没有水王!!!" << endl;

}

运行截图:

四、总结

这次课后作业的思路很重要,相邻比较,相同加1,不同消除的方法比起遍历的方法要简单太多,当比较完后,留下次数最多的ID,再比较一下这个次数是不是总数的一半以上就可以判断水王的存在。

原文地址:https://www.cnblogs.com/me-tts/p/5513546.html