题解:UVA11223 O: dah dah dah!

· · 题解

感谢第一篇题解帮助我解决了格式问题。

题意

给你 t 串摩斯密码,让你求明文。

思路

模拟。

原本是想每读入一个密文就输出一个明文的,结果 WA 了。

于是改用 getline,每输入一行暗文就按照题面上的表格输出一行明文。

代码


#include<iostream>
using namespace std;
int t;
char change(string s){
    if(s==".-")return 'A';
    else if(s=="-...")return 'B';
    else if(s=="-.-.")return 'C';
    else if(s=="-..")return 'D';
    //中间省略
    else if(s==".----.")return '\'';//要用\'才能输出字符'
    //中间省略
    else if(s=="..--.-")return '_';
    else if(s==".-..-.")return '\"';
    else if(s==".--.-.")return '@';
    else return 'e';//如果这串密文不是一串摩斯密码,返回'e'
}
int main(){
    cin>>t;
    getchar();//要过滤掉换行
    for(int i=1;i<=t;i++){
        if(i!=1) cout<<endl;//控制格式
        string s;
        getline(cin,s);//输入整行密文
        string n="",m="";
        for(unsigned j=0;j<s.size();j++){
            if(s[j]=='-'||s[j]=='.') n+=s[j];//如果这个字符是.或-就加上
            else{
                if(change(n)!='e') m+=change(n);//判断这串密文是不是摩斯密码。如果是就加上
                n="";//清空
            }
            if(s[j]==' '&&s[j+1]==' ') m+=' ';//连续两个空格相当于明文里的一个空格
        }
        cout<<"Message #"<<i<<endl;
        if(change(n)!='e') m+=change(n);//可能会漏掉最后一串密文
        cout<<m<<endl;
    }
}