zoukankan      html  css  js  c++  java
  • BZOJ 1640 [Usaco2007 Nov]Best Cow Line 队列变换:贪心【字典序最小】

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1640

    题意:

      给你一个长度为n的字符串。

      你可以将原串的首字母或尾字母移动到新串的末尾。

      让你输出字典序最小的新串。

    题解:

      贪心。

     

      三种情况:

        (1)c[head] < c[tail]

          输出c[head],head++。

        (2)c[head] > c[tail]

          输出c[tail],tail--。

        (3)c[head] == c[tail]

          选head和tail并不等价。

          比如原串为"CBAC",明显选tail更优,因为选tail能够更快地选到'A',让字典序更小。

          所以需要不断地"head++,tail--",直到c[head] != c[tail]的时候停止,然后选小的。

    AC Code:

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <string.h>
     4 #define MAX_N 2005
     5 
     6 using namespace std;
     7 
     8 int n;
     9 int head,tail;
    10 char c[MAX_N];
    11 
    12 int main()
    13 {
    14     cin>>n;
    15     head=0;
    16     tail=n-1;
    17     for(int i=0;i<n;i++)
    18     {
    19         cin>>c[i];
    20     }
    21     for(int i=0;i<n;i++)
    22     {
    23         if(i!=0 && i%80==0) cout<<endl;
    24         if(c[head]<c[tail]) cout<<c[head++];
    25         else if(c[head]>c[tail]) cout<<c[tail--];
    26         else
    27         {
    28             int lef=head;
    29             int rig=tail;
    30             int res=0;
    31             while(lef<=rig)
    32             {
    33                 if(c[lef]<c[rig])
    34                 {
    35                     res=-1;
    36                     break;
    37                 }
    38                 if(c[lef]>c[rig])
    39                 {
    40                     res=1;
    41                     break;
    42                 }
    43                 lef++;
    44                 rig--;
    45             }
    46             if(res==0 || res==-1) cout<<c[head++];
    47             else cout<<c[tail--];
    48         }
    49     }
    50 }
  • 相关阅读:
    如何把一个一般的git库变成“裸库”?
    MacOSX下杀掉sudo进程
    nginx FastCGI错误Primary script unknown解决办法
    Lua继承userdata
    Unity图文混排
    C++轻量级跨平台文件系统API
    lua_next()
    重载方法匹配算法
    C++模板函数只能全特化不能偏特化
    xcode离线安装包下载
  • 原文地址:https://www.cnblogs.com/Leohh/p/7622830.html
Copyright © 2011-2022 走看看