HDU2609 How many(字符串的最小表示+set)

来源:互联网 发布:手机淘宝6.6.0版本 编辑:程序博客网 时间:2024/05/28 09:32

How many

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3178 Accepted Submission(s): 1394

Problem Description
Give you n ( n < 10000) necklaces ,the length of necklace will not large than 100,tell me
How many kinds of necklaces total have.(if two necklaces can equal by rotating ,we say the two necklaces are some).
For example 0110 express a necklace, you can rotate it. 0110 -> 1100 -> 1001 -> 0011->0110.

Input
The input contains multiple test cases.
Each test case include: first one integers n. (2<=n<=10000)
Next n lines follow. Each line has a equal length character string. (string only include ‘0’,’1’).

Output
For each test case output a integer , how many different necklaces.

Sample Input
4
0110
1100
1001
0011
4
1010
0101
1000
0001

Sample Output
1
2

字符串的最小表示:对于一个字符串,旋转可得到的最小字典序串。

存一下求字符串最小表示的模板,模拟一下过程,很好理解

对于本题,求出每一个串的最小表示,然后都插入到set里,输出一下size即可

#include<stdio.h>#include<algorithm>#include<iostream>#include<string.h>#include<vector>#include<set>using namespace std;const int N=1e4+100;int min_express(string x){    int i=0,j=1,k=0;    int len=x.size();    while(i<len&&k<len&&j<len)    {        int t=x[(j+k)%len]-x[(i+k)%len];        if(t==0)k++;        else        {                if(t<0) i+=k+1;                else j+=k+1;            if(i==j)j++;            k=0;        }    }    return min(i,j);}int main(){    std::ios::sync_with_stdio(false);    cin.tie(0);    int n;    while(cin>>n)    {        set<string>xp;        string s;        for(int i=0; i<n; i++)        {            cin>>s;            int ans_min=min_express(s);            int len=s.size();            string ans="";            for(int j=ans_min; j<ans_min+len; j++)                ans+=s[j%len];            xp.insert(ans);        }        cout<<xp.size()<<endl;    }    return 0;}
原创粉丝点击