1828: Dictionary
1828: Dictionary
题意:有a,b,c,d,e,f,g,h,i组成的全排列(字典序),然后给出单词,问这个单词是第几个单词。
分析:显然可以直接用STL里面的next_permutation来就出全排列,然后拍一下序,然后对于每一个查找,可以直接用二分查找位置。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
string s[400000];
char a[9]={'a','b','c','d','e','f','g','h','i'};
int bs(string tmp){//二分查找
int lo=0,hi=362880;
int mid;
while (lo<=hi){
mid=(hi+lo)/2;
if (s[mid]==tmp)return mid+1;
else if (s[mid]>tmp){
hi=mid-1;
}
else {
lo=mid+1;
}
}
}
int main ()
{
int tot=0;
s[tot++]=(string)a;
while (next_permutation(a,a+9)){//用STL里面的函数生成全排列
s[tot]=(string)a;
tot++;
}
sort (s,s+tot); //排序
int t;
while (scanf ("%d",&t)!=EOF){
char tmp[15];
while (t--){
scanf ("%s",tmp);
int ans=bs((string)tmp);
printf ("%d\n",ans);
}
}
return 0;
}

本文介绍了一种使用C++ STL中的next_permutation函数生成全排列的方法,并通过二分查找确定给定单词在字典序中的位置。适用于编程竞赛中涉及字典序排列的问题。
321

被折叠的 条评论
为什么被折叠?



