zoukankan      html  css  js  c++  java
  • ural Cipher Message

    Cipher Message
    Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

    Description

    Müller tried to catch Stierlitz red-handed many times, but always failed because Stierlitz could ever find some excuse. Once Stierlitz was looking through his email messages. At that moment, Müller entered secretly and watched a meaningless sequence of symbols appear on the screen. “A cipher message,” Müller thought. “UTF-8,” Stierlitz thought.
    It is known that Stierlitz ciphers messages by the following method.
    1. He deletes all spaces and punctuation marks.
    2. He replaces all successive identical letters by one such letter.
    3. He inserts two identical letters at an arbitrary place many times.
    Try to restore a message as it was after the second step. For that, remove from the message all pairs of identical letters inserted at the third step.

    Input

    The only input line contains a message ciphered by Stierlitz. The message consists of lowercase English letters and its length is at most 200000.

    Output

    Output the restored message.

    Sample Input

    inputoutput
    wwstdaadierfflitzzz
    stierlitz

    解答:

    首先采用了最直接的做法,这种做法时间复杂度为O(n2)

     1 #include <iostream>
     2 #include <cstring>
     3 using namespace std;
     4 
     5 int main(){
     6     string data;
     7     cin>>data;
     8     int a;
     9     while(1){
    10         a=0;
    11         for(int i=0;i<data.length();i++){
    12             if(data[i]==data[i+1]){
    13                 a=1;
    14                 data.erase(i,2);
    15             }
    16         }
    17         if(a==0){
    18             break;
    19         }
    20     }
    21     cout<<data;
    22     
    23 } 

    结果超时,于是用下面的方法另起炉灶。时间复杂度为O(n),遂AC

     1 #include <iostream>
     2 #include <cstring>
     3 using namespace std;
     4 #define N 200002
     5 
     6 int main(){
     7     char  data[N];
     8     gets(data);
     9     char temp[N];
    10     memset(temp,0,sizeof(temp));
    11     
    12     int fir=-1;
    13     int lon=strlen(data);
    14     for(int i=0;i<lon;i++){
    15         if(data[i] != temp[fir] ){
    16             temp[++fir]=data[i];
    17         }
    18         else{
    19             fir--;
    20         }
    21     }
    22     
    23     for(int i=0;i<=fir;i++){
    24         cout<<temp[i];
    25     }
    26     
    27     return 0;
    28 }
  • 相关阅读:
    “==” 和 Equals()
    数据持久层的设计
    Jquery Validation :多个按钮都需要做提交验证的解决方案
    留住异常的堆栈信息【throw ex 和 throw 的区别】
    [转] eval() may be evil
    框架结构和脚本跨域的问题
    ue4 材质MipLevels
    spring+json+jquery
    a different object with the same identifier value was already associated with the session错误
    kali 更新国内apt源 (转)
  • 原文地址:https://www.cnblogs.com/liugl7/p/4833952.html
Copyright © 2011-2022 走看看