1056 IMMEDIATE DECODABILITY

题目链接: http://poj.org/problem?id=1056

题意: 给定编码集, 判断它是否为可解码(没有任何一个编码是其他编码的前缀).

分析: 简单题目, 遍历一遍即可, 只需判断两个编码是否互为前缀或相等即可.

代码:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
string line;
vector<string> vs;

bool isPrefix(string s1,string s2){
    int len1 = s1.length();
    int len2 = s2.length();
    int i;
    if(len1<len2){ //判断s1 是否为s2前缀
        for(i=0;i<len1;++i){
            if(s1.at(i) != s2.at(i))
                break;
        }
        if(i == len1)
            return true;
        else 
            return false;
    }
    if(len1 > len2)
        return isPrefix(s2,s1);
    if(len1 == len2){
        return s1 == s2;
    }
}

int main(){
    int sets = 0;
    while(cin>>line){
        sets++;
        vs.clear();
        // enter a set
        while(line.at(0)!='9'){
            vs.push_back(line);
            cin>>line;
        }
        int len = vs.size();
        int i,j;
        for(i=0;i<len;++i){
            for(j=0;j<len;++j){
                if(i!=j && isPrefix(vs[i],vs[j])){
                    break;
                }
            }
            if(j!=len)
                break;
        }
        if(i!=len)
            cout<<"Set "<<sets<<" is not immediately decodable"<<endl;
        else
            cout<<"Set "<<sets<<" is immediately decodable"<<endl;
        //clear to accpet the new set.
        vs.clear();
    }
    return 0;
}
posted @ 2015-10-17 11:22  roger9567  阅读(126)  评论(0编辑  收藏  举报