Updating a Dictionary——UVA - 12504

也可以查看这里

题目链接

题目大意:给出一个旧词典和新词典,词典是以键值对的方式存储的,输出二者的变化:
1、如果至少包含一个新增键,那么先输出一个+,后面输出所有新增的键,用,分隔,按字典序上升输出
2、如果至少包含一个删除键,那么先输出一个-,后面输出所有删除的键,用,分隔,按字典序上升输出
3、如果至少包含一个修改键,那么先输出一个*,后面输出所有修改的键,用,分隔,按字典序上升输出

其实这个题手暴也可以过去的,但是看到了一个dalao写的方法比较好,所以就写一下题解
我们其实可以用stringstream来解决输入,输入时以string输入,接着讲这个字符串中"{"、"}"、":"、","的位置全换成空格,
再接着只要用stringstream输入就行了,后面只要用三个set保存每一个结果即可

代码:

#include <set>
#include <map>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>

using namespace std;

string s , t;
set < string > add , del , alt;
map < string , string > mp1 , mp2;

inline void init()
{
    mp1.clear();
    mp2.clear();
    add.clear();
    del.clear();
    alt.clear();
}

void solve(string a , map < string , string > & m)
{
    //首先将字符串中特定的字符换成空格
    //注意这里循环里面不能写i < a.length()
    int len = a.length();
    for(int i = 0 ; i < len ; ++ i)
        if(a[i] == '{' || a[i] == '}' || a[i] == ',' || a[i] == ':')
            a[i] = ' ';
            
    stringstream in(a);
    
    string x , y;
    while(in >> x >> y) m[x] = y;
}

int main(void)
{
    int T;
    cin >> T;getchar();
    while(T--)
    {
        init();//初始化
        cin >> s;//输入旧词典
        cin >> t;//输入新词典
        
        //根据字符串构建词典
        solve(s , mp1);
        solve(t , mp2);
        
        for(auto i : mp2)
            if(mp1.find(i.first) == mp1.end()) add.insert(i.first);
            
        for(auto i : mp1)
            if(mp2.find(i.first) == mp2.end()) del.insert(i.first);
            else if(mp2[i.first] != i.second) alt.insert(i.first);
        
        if(add.empty() && del.empty() && alt.empty())
        {
            puts("No changes");
            puts("");
            continue;
        }
        
        if(!add.empty())
        {
            cout << "+";
            for(auto i : add)
            {
                if(i != *add.begin()) cout << ",";
                cout << i;
            }
            puts("");
        }
        
        if(!del.empty())
        {
            cout << "-";
            for(auto i : del)
            {
                if(i != *del.begin()) cout << ",";
                cout << i;
            }
            puts("");
        }
        if(!alt.empty())
        {
            cout << "*";
            for(auto i : alt)
            {
                if(i != *alt.begin()) cout << ",";
                cout << i;
            }
            puts("");
        }
        puts("");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值