• 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 }
  • 相关阅读:
    分布式缓存HttpRuntime.cache应用到单点登陆中_优化登陆
    ID Codes
    Smith Numbers经典
    青蛙的约会
    exp_euler两种形式int,void(扩展欧几里得算法)可求最大公约数,二元一次方程的解
    A/B
    Raising Modulo Numbers
    Brave balloonists 求素因子的个数
    排列
    Anagram
  • 原文地址:https://www.cnblogs.com/liugl7/p/4833952.html
Copyright © 2020-2023  润新知