您的位置:首页 > 编程语言

编程之美--发帖水王及扩展问题

2011-04-05 15:24 260 查看
重点是理解:当有一半都是同一个ID时,同时删除两个ID得到的结果最大ID已然占一半以上。

 

剩下的在代码中有些注释,贴之:

 

//This file is used to test the size of
//different char type
#include <iostream>
using namespace std;
int FindMost(int *iVec,int n)
{
int nTimes = 0;
int result;
for (int i = 0; i<n;++i)
{
if(!nTimes)
{
result = iVec[i];
++nTimes;
}
else
{
if (result == iVec[i])
++nTimes;
else
--nTimes;
}
}
cout<<"nTimes: "<<nTimes<<endl;
return result;
}
void FindThreeMost(int *data,int n)
{
int nTimes[3] = {0,0,0};
int result[3] = {0,0,0};
bool flag = false;
for (int i = 0; i<n;++i)
{
for(int j = 0; j< 3; ++j)
{
if (!nTimes[j])
{
result[j] = data[i];
++nTimes[j];
flag = true;
break;
}
}
if(flag)
continue;
if(result[0]  == data[i] )
{
++nTimes[0];
}
else 	if(result[1]  == data[i] )
{
++nTimes[1];
}
else if(result[2]  == data[i] )
{
++nTimes[2];
}
else
{
--nTimes[0];--nTimes[1];--nTimes[2];
if(nTimes[0]&&nTimes[1]&&nTimes[2] == 0)
flag = false;
}
}
for (int i = 0;i<3;++i)
cout<<result[i]<<endl;
}
int main()
{
int data[20] = {1,2,1,3,1,4,1,5,1,6,1,7,1,1,1,1,1,9,10,11};
int da[20] = {1,2,3,4,1,2,3,5,1,2,3,6,1,2,3,7,1,2,3,8};
cout<<FindMost(data,20)<<endl;
FindThreeMost(da,20);
return 0;
}


 

上述代码中的flag是用来判定当前的循环是否执行的赋值操作,如果不是赋值操作才会进入到下面的语句中。

在这个时候真的觉得python中的for...else循环设计是最出彩的设计……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 扩展 python file