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

来源:互联网 发布:车贷app管理系统源码 编辑:程序博客网 时间:2024/05/22 16:04

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

inputoutput
61 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";}




1 0
原创粉丝点击