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

来源:互联网 发布:淘宝网表带 编辑:程序博客网 时间:2024/05/20 23:40
#include <iostream>using namespace std;#define N 3bool GetMinlen(int *a,int m,int &shortHead,int & shortlen){int start=0,end = 0;int countColor = 0;int *colorArray = new int[N];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向后移动,直到有一个颜色数为0while(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;}

原创粉丝点击