The strongest lineup

5780: The strongest lineup

Time Limit: 1 Sec   Memory Limit: 128 MB
Commits: 206   Resolved: 54
[ Commit ][ Status ][ Discussion Board ][Assert By: admin ]

Topic description

With the newly exchanged hero card, Xiao Li happily prepared to have a PK with his classmates.
The rules of their game are very simple. Both sides circle their cards in a circle, and then specify a starting point, and take the card clockwise from the card. The first character that is different is compared, and the comparison rule is a<b<…<z) who will win. For specific rules, please refer to the example. Although Xiao Li's cards are very good now, can you help him quickly calculate the starting position so that he can send the strongest lineup.
 

enter

The first line is n (1<=n<=30000), which means there are n cards in total.
The second line consists of n lowercase letters separated by a space, indicating the starting sequence of a given circle of cards.
 

output

Only an integer, can get the starting position of the smallest lexicographical string. If there are multiple positions starting with the same string, the smallest position is output, and the first position starts from 1.

sample input

4
b c a b

Sample output

3

hint

The strings taken out from the four positions are bcab, cabb, abbc, and bbca. Obviously, the minimum position is 3.

 

******************************************************************************************************************************************************************************************************

Code:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

intmain ()
{
    int n;
    char str[30005];
    scanf("%d",&n);
    //getchar();
    char x[50];
    for(int i=0;i<n;i++)   //读取
    {
        scanf("%s",x);
        str[i] = x[0];
        //str[i] = getchar();
        //getchar();
    }
    str [n] = ' \ 0 ' ;

    int ans = 0 ;    // record the smallest answer 
    for ( int i= 1 ;i<n;i++ )
    {
        if(str[i]<str[ans])
            ans = i;
         else  if (str[i]==str[ans]) // == 
        {
             for ( int j=ans+ 1 ,k = i+ 1 ,p= 0 ;p<n;p++,j++,k++) // j is the smallest next bit k is the next bit currently traversed 
            {
                 if (str[j%n]<str[k%n]) // the original smallest string is small 
                {
                     break ;
                }
                else  if (str[j%n]>str[k%n]) // The current bit string is small 
                {
                    ans = i;
                    break;
                }
            }
        }
    }
    printf("%d",ans+1);
}

//wa many times I started to use n*n violent solution and found that it would time out and then changed to the above method, but I don't know why I read it with getchar(), and I changed it to scanf("%s") before A.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324864424&siteId=291194637