南阳 oj Registration system 题目991

1、题目信息:

Registration system

时间限制:1000 ms |  内存限制:65535KB

难度:2

描述

A new e-mail service "Berlandesk"is goingto be opened in Berland in the near future.Thesite administration wants to launch their project as soon as possible, that'swhythey askyou to help. You're suggested to implement the prototype of site registrationsystem.The system should workon the following principle.

Each time a new user wants to register, hesends tothe system a request with his name.Ifsuch a name does not exist in the system database, it is inserted intothedatabase, and the user gets the response OK, confirmingthe successful registration. If the name already exists in thesystem database, the systemmakes up a new user name, sends it to the user as a prompt and also inserts the promptintothe database. The new name is formed by the following rule. Numbers, starting with 1, areappended one afteranother to name (name1,name2, ...), among these numbers the least is found so that namei does not yet exist in thedatabase.

输入

The first line contains number n (1 ≤ n ≤ 105). The followingn lines contain the requests to the system. Each request is a non-empty line, and consists of not more than1000 characters, which are all lowercase Latin letters.

输出

Print n lines, which are system responses to therequests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

样例输入

4
abacaba
acaba
abacaba
acab

样例输出

OK
OK
abacaba1
OK

题目的大致意思是:

    首先输入测试组数n,对于后面输入的n组姓名,如果数据库中不存在就输出OK,否则输出对应namei(i=1,2,……)。

2、思路

方法一:set集合

    1)使用c++的STL的set类,利用集合自动去除重复元素

    2)对于存在的元素多次判断,需要递增名字后面的数字

方法二:map映射集合

    利用map<string,int>通过查询string键来判断int的值

3、代码

set代码:

#include <set>
#include <string>
#include <iostream>
using namespace std;
int main(){
    int n,len,i;
    string str,str1;
    set<string>s;
    cin>>n;
    while(n--){
        cin>>str;
        i=0;
        len=s.size();
        s.insert(str);
        if(len!=s.size()){//如果插入新值后长度有变化
            cout<<"OK"<<endl;
        }
        else{
            while(len==s.size()){//直到集合长度有变化
                i++;
                str1=str;
                str1+=char(i+48);//插入转换成ascii的数字
                s.insert(str1);
            }
            cout<<str<<i<<endl;
        }
    }
    return 0;
}

map代码:

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
    int n,len,i;
    string str,str1;
    map<string,int>m;
    cin>>n;
    while(n--){
        cin>>str;
        if(!m.count(str)){//count函数判断str是否在map中
            m[str]=0;
            cout<<"OK"<<endl;
        }else {
            m[str]++;
            cout<<str<<m[str]<<endl;
        }
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/sicauliuy/article/details/80153089
今日推荐