码迷,mamicode.com
首页 > 其他好文 > 详细

Timus 2011. Long Statement 排列组合的运用

时间:2014-04-27 21:36:58      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:timus   2011. long statement   排列组合的运用   

Nikita, a schoolboy, is currently taking part in one of programming contests. He is really upset because all the problem statements are so long and unclear. So he took the statement of the first problem and cut it into pieces in such a way that each piece contained exactly one letter. After that, he threw away all pieces with letter other than “a”, “b” or “c”. Now he has only npieces and wants to compile from them his own statement that should be shorter and clearer than the original one.
The new statement should be a single word compiled from all n letters placed in some order. Nikita wondered if he can compile at least six different words of length n from the letters. If this is not true, he will be ruined and will start solving other problems. Help Nikita to answer this monumental question!

Input

The first line contains an integer n that is the number of pieces with letters (1 ≤ n ≤ 100). The second line describes these pieces as n integers from 1 to 3. 1 represents a piece with letter “a”, 2 represents a piece with letter “b”, 3 represents a piece with letter “c”.

Output

If Nikita can compile at least six different words of length n, output “Yes”. Otherwise output “No”.

Sample

input output
6
1 2 2 3 3 3
Yes


本题我使用了permutation的知识去解决。

就是把 1 2 2 3 3 3 看着是一个排列,然后求6次下一个排列,如果无重复,那么就是Yes,如果有重复,那么就是No了。

求排序的时间效率是O(n),所以本算法的速度还是相当快的。

能够运用上学过的知识,感觉真是太好了。

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

bool permuteLongStatement(vector<int> &rs, vector<int> &tmp)
{
	int i = tmp.size() - 2;
	for ( ; i >= 0 && tmp[i] >= tmp[i+1]; i--);
	if (i < 0)
	{
		reverse(tmp.begin(), tmp.end());
		return tmp != rs;
	}
	int j = tmp.size() - 1;
	for ( ; tmp[j] <= tmp[i]; j--);
	swap(tmp[i], tmp[j]);
	reverse(tmp.begin()+i+1, tmp.end());
	return tmp != rs;
}

void LongStatement2011()
{
	int n;
	cin>>n;
	vector<int> rs(n);
	for (int i = 0; i < n; i++)
	{
		cin>>rs[i];
	}
	vector<int> tmp(rs);
	bool ok = true;
	for (int i = 0; i < 5; i++)//注意这里是5不是6,因为第一个不permute前算一个
	{
		if (!permuteLongStatement(rs, tmp))
		{
			ok = false;
			break;
		}
	}
	if (ok) cout<<"Yes";
	else cout<<"No";
}




Timus 2011. Long Statement 排列组合的运用

标签:timus   2011. long statement   排列组合的运用   

原文地址:http://blog.csdn.net/kenden23/article/details/24600119

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!