题意:在本题中,字典是若干键值对,其中键为小写字母组成的字符串,值为没有前导零或正号的非负整数(-4, 03, 77都是非法的,注意该整数可以很大)。输入一个旧字典和一个新字典,计算二者变化。输入的两个字典中键都是唯一的,但是排列顺序任意。具体格式为(注意字典格式中不含任何空白字符):{key:vaule,key:vlue,...,key:vaule}
输入包含两行,各包含不超过100个字符,即旧字典和新字典。输出格式如下:
囗 如果至少有一个新增键,打印一个“+”号,然后是所有新增键,按字典序从小到大:
囗 如果至少有一个删除键,打印一个“-” 号,然后是所有删除键,按字典序从小到大排列。
口 如果至少有一个修改键,打印一个“*” 号,然后是所有修改键,按字典序从小到大排列。
口 如果没有任何修改,输出No changes。
思路:输入以后,处理字符串,用map<string, string> mp[2]存储,mp[0]存旧字典,mp[1]存新字典,然后对比两个字典。
注意:字典可能会为空,此时不要往map中插入""字符串。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 105;
map<string, string> mp[2];
string ans[MAXN];
bool has_out;
void work(string s, int id)
{
string key, value;
bool flag = false;
for (int i = 1; i < s.size(); i++)
{
if (s[i] == ',' || s[i] == '}')
{
if (!key.empty()) mp[id][key] = value;
key.clear(); value.clear();
flag = false;
continue;
}
if (s[i] == ':') { flag = true; continue; }
if (!flag) key += s[i];
if (flag) value += s[i];
}
}
void putout(char c, int cnt)
{
has_out = true;
cout << c << ans[0];
for (int i = 1; i < cnt; i++)
cout << "," << ans[i];
cout << endl;
}
int main()
{
int T; scanf("%d", &T);
while (T--)
{
mp[0].clear(); mp[1].clear();
has_out = false;
string a, b;
cin >> a >> b;
work(a, 0); work (b, 1);
int cnt = 0;
for (auto i: mp[1])//增加的
if (!mp[0].count(i.first)) ans[cnt++] = i.first;
if (cnt) putout('+', cnt);
cnt = 0;
for (auto i: mp[0])//删除的
if (!mp[1].count(i.first)) ans[cnt++] = i.first;
if (cnt) putout('-', cnt);
cnt = 0;
for (auto i: mp[0])//替换的
{
for (auto j: mp[1])
{
if (i.first == j.first && i.second != j.second)
ans[cnt++] = i.first;
}
}
if (cnt) putout('*', cnt);
cnt = 0;
if (!has_out) cout << "No changes" << endl;
cout << endl;
}
return 0;
}
/*
4
{a:3,b:4,c:10,f:6}
{a:3,c:5,d:10,ee:4}
{x:1,xyz:123456789123456789123456789}
{xyz:123456789123456789123456789,x:1}
{first:1,second:2,third:3}
{third:3,second:2}
{}
{provided:1,table:1,show:9,name:9,it:3,other:0,john:9,down:9,change:5,is:7,digital:7}
*/