您的位置:首页 > 其它

一串首尾相连的珠子(m个),有N种颜色(N<=10),设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短

2014-11-14 00:00 651 查看
#include <iostream>
using namespace std;

#define N 3

bool GetMinlen(int *a,int m,int &shortHead,int & shortlen)
{
int start=0,end = 0;
int countColor = 0;
int *colorArray = new int
;
shortlen = m;
shortHead = 0;

for(int i =0;i< N;i++)
{
colorArray[i] = 0;
}

while(start < m)
{
//向后搜索直至所有的颜色均出现
while(countColor < N && (end+1)%m !=start)
{
if(colorArray[a[end]]++ == 0)
{
countColor++;
}

if(countColor <N)
{
end=(end+1)%m;
}
}

if(countColor != N)
{
cout << "珠子颜色数少于所要找的数目"<<endl;
return false;
}

//start向后移动,直到有一个颜色数为0
while(start<m)
{
if(colorArray[a[start]] > 1)
{
colorArray[a[start]]--;
start++;
}
else
{
break;
}
}

if(shortlen > end - start +1)
{
shortlen = end -start +1;
shortHead = start;
}

colorArray[a[start]]--;
start++;
countColor--;
end = (end+1)%m;
colorArray[a[end]]++;
}

return true;
}

int main()
{
int start,end;
int m[] ={0,1,1,1,2,0,1,2,1,2,0};
GetMinlen(m,11,start,end);
cout << start << " " <<end<< endl ;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 include
相关文章推荐