最短完备子序列——包含T全部元素的最小子窗口

////、、、、、、

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

bool MinWindow(vector s, vector t, int &startWin, int &endWin) {
	int slen = s.size();
	int tlen = t.size();
	if (slen <= 0 || tlen <= 0) {
		return false;
	}
	// 存储T中不同字符的总数
	int needFind[256] = { 0 };
	for (int i = 0; i < tlen; ++i) {
		++needFind[t[i]];
	}
	// 不在T中的元素设置为-1
	for (int i = 0; i < 256; ++i) {
		if (needFind[i] == 0) {
			needFind[i] = -1;
		}
	}
	int minWinLen = INT_MAX;
	// 队列数组,每个不同的字符都对应一个队列
	queue q[256];
	// 第一个元素和最后一个元素表明了窗口的开始和结束位置
	map m;
	int val;
	for (int i = 0; i < slen; ++i) {
		val = s[i];
		// 跳过不在T中的元素
		if (needFind[val] == -1) {
			continue;
		}
		// 字符放入队列
		if (q[val].size() < needFind[val]) {
			q[val].push(i);
			m[i] = val;
		}
		// 取代队列中的字符,更新map中对应元素
		else {
			int idxToErase = q[val].front();
			map::iterator it = m.find(idxToErase);
			m.erase(it);
			m[i] = val;
			q[val].pop();
			q[val].push(i);
		}
		if (m.size() == tlen) {
			int end = m.rbegin()->first;
			int start = m.begin()->first;
			int winLen = end - start + 1;
			if (winLen < minWinLen) {
				minWinLen = winLen;
				startWin = start;
				endWin = end;
			}
		}
	}
	return (m.size() == tlen);
}

int main() {
	int N, M;
	int data;
	vector s;
	vector t;
	while (cin >> N >> M) {
		for (int i = 0; i < N; i++) {
			cin >> data;
			s.push_back(data);
		}
		for (int i = 1; i <= M; i++) {
			t.push_back(i);
		}
		int start, end;
		bool result = MinWindow(s, t, start, end);
		if (result) {
			cout << end - start + 1 << endl;
		}
		else {
			cout << 0 << endl;
		}
	}
	return 0;
}

 

 

 

转自: https://blog.csdn.net/yangwenxue_admin/article/details/44568069

你可能感兴趣的:(algorithm)