STL——字典排序问题next_permutation(a.begin(),a.end())

在做每周一赛的时候,有一道我觉得题目想起来不算特别难,但是实现起来相当烦琐。而且还AC不了,我先po上我自己写的代码(啰嗦死了),勿喷。

原题链接:http://soj.me/7530

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string SS[6];
	char crosswords[3][3];
	string answer;
	string result;
	int i,j,k,l,t,m;
	int symbol;
	bool judge = false;
	for(i = 0;i < 6;i++)
	{
		cin >> SS[i];
	}
	for(i = 0;i < 6;i++)
	{
		for(j = 0;j < 3;j++)
		{
			char temp = SS[i][j];
			bool tt = false;
			for(k = 0;k < 6;k++)
			{
				if(temp == SS[k][0])
				{
					tt = true;
					break;
				}
			}
			if(tt == true)
				continue;
			else
				break;
		}
		if(j >= 3)
		{
			answer = SS[i];   //表明已经找到了字典序排序最低的符合第一个要求的答案
			symbol = i;
			for(l = 0;l < 3;l++)
				crosswords[0][l] = answer[l];  //填入九宫格第一行
			for(l = 0;l < 3;l++)
			{
				string aa;
				for(t = 0;t < 6;t++)
				{
					if(answer[l] == SS[t][0] && t !=  symbol)
					{
						aa = SS[t];
						for(m = 0;m < 3;m++)
						{
							crosswords[m][l] = aa[m];
						}
					}
				}
			}
			//开始检测九宫格的正确性
			bool cc = false;
			for(l = 0;l < 6;l++)
			{
				if(crosswords[1][0] == SS[l][0])
				{ 
					for(m = 0;m < 3;m++)
					{
						if(crosswords[1][m] != SS[l][m])
							break;
					}
				}
				if(m >= 3)
				{
					cc = true;
					break;
				}
			}
			if(cc == false)
				break;
			for(l = 0;l < 3;l++)

			cc = false;
			for(l = 0;l < 6;l++)
			{
				if(crosswords[2][0] == SS[l][0])
				{ 
					for(m = 0;m < 3;m++)
					{
						if(crosswords[2][m] != SS[l][m])
							break;
					}
				}
				if(m >= 3)
				{
					cc = true;
					break;
				}
			}
			if(cc == true)
			{
				judge = true;
				break;
			}
		}
	}
	if(judge == true)
	{
		for(i = 0;i < 3;i++)
		{
			for(j = 0;j < 3;j++)
				cout << crosswords[i][j];
			cout << endl;
		}
	}
	else
		cout << 0 << endl;
	return 0;
}

 结果在苦苦挣扎之后,我决定求助大神,发现这道题的解法真是碉堡了。大神提供的代码不仅简介漂亮,而且通俗易懂。

现在想起来,我想复杂了,其实这道题目就用两个字便可以击破:暴力。

其实真不用什么高效的算法,直接暴力解法就好,题目要求写出最少字典序的方案,所以之前还没有用过STL里面的字典排序next_permutation()函数。

这里便发挥了作用。

代码实现:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {

	vector<string> a;
	a.resize(6);
	bool ok = false;

	for (int i = 0; i < 6; ++i)
		cin >> a[i];
	
	do {
		string stupci[3];
		
		for (int i = 0; i < 3; ++i)
			for (int j = 0; j < 3; ++j)
				stupci[j] += a[i][j];
				
		ok = true;
		for (int i = 0; i < 3; i++)
			if (stupci[i] != a[i + 3])
				ok = false;

		if (ok) {
			for (int i = 0; i < 3; ++i)
				cout << a[i] << endl;
			break;
		}
			
	} while (next_permutation(a.begin(), a.end()));
	
	if (!ok)
		cout << 0 << endl;
}

 

posted @ 2013-03-12 19:06  中大黑熊  阅读(1070)  评论(1编辑  收藏  举报