寻找水王(2)

求解内容极其相似,相同的思路进行求解即可。同时删除4个不同的ID后,剩余数据中3个多数id仍然是多数ID。

上题只需要一个结果,而现在需要3个结果,上题用到的nTimes,也应改为3个计数器。现在我们需要3个变量来记录当前遍历过的3个不同的ID,而nTimes的3个元素分别对应当前遍历过的3个ID出现的个数。如果遍历中有某个ID不同于这3个当前ID,我们就判断当前3个ID是否有某个的nTimes为0,如果有,那这个新遍历的ID就取而代之,并赋1为它的遍历数(即nTimes减1),如果当前3个ID的nTimes皆不为0,则3个ID的nTimes皆减去1。

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int candidate[3];
 6 int count[3] = {0};
 7 
 8 int input[100];
 9 int num = 0;
10 
11 int main()
12 {
13     cout<<"please input"<<endl;
14     int t;
15     while(cin>>t)
16     {
17         if (t == -1)
18             break;
19         input[num++] = t;
20     }
21 
22     bool flag = false;
23 
24     for (int i = 0;i < num;i++)
25     {
26         flag = false;
27         for (int j = 0;j < 3;j++)
28         {
29             if (count[j] == 0)
30             {
31                 continue;
32             }
33             if (candidate[j] == input[i])
34             {
35                 count[j]++;
36                 flag = true;
37             }
38         }
39 
40         if (flag == true)
41         {
42             continue;
43         }
44 
45         for (int j = 0;j < 3;j++)
46         {
47             if (count[j] == 0)
48             {
49                 candidate[j] = input[i];
50                 count[j]++;
51                 flag = true;
52                 break;
53             }
54         }
55 
56         if (flag == true)
57         {
58             continue;
59         }
60 
61         for (int j = 0;j < 3;j++)
62         {
63             count[j]--;
64         }
65 
66     }
67 
68     cout<<count[0]<<" "<<count[1]<<" "<<count[2]<<endl;
69     cout<<candidate[0]<<" "<<candidate[1]<<" "<<candidate[2]<<endl;
70 }

 

posted @ 2016-05-26 17:30  代码小逸  阅读(167)  评论(0编辑  收藏  举报