题目:UVa 12504 Updating a Dictionary
分析:
键值对可用map来处理,即map[ key ] = value。
因为有三种情况要讨论,股分别用set保存对应变化的键值,顺便排序。
读入需要注意,通过冒号来区分key和value,不同键值对用 ',' 和 '}‘区分,而 '}' 代表此行的读入停止。
代码:
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cctype>
#include <sstream>
using namespace std;
map<string, string> key;
map<string, int> vis;
set<string> add, rem, cha;
void disp(set<string> x) {
int len = x.size(), i = 0;
for (set<string>::iterator it = x.begin(); it != x.end(); it++, i++) {
cout << *it;
if (i < len - 1)
cout << ',';
}
cout << '\n';
}
int main() {
int t;
cin >> t;
while (t--) {
key.clear();
vis.clear();
add.clear();
rem.clear();
cha.clear();
char c;
int flag = 0;
string a, b, s;
cin >> s;
stringstream ss(s);
while (ss >> c) {
// cout << "c:" << c << '\n';
if (!flag) {
if (isalpha(c))
a.push_back(c);
else if (c == ':')
flag = !flag;
}
else {
if (isalnum(c))
b.push_back(c);
else {
flag = !flag;
key[a] = b;
vis[a] = 0;
// cout << "a:" << a << ", b:" << b << '\n';
a.clear();
b.clear();
if (c == '}')
break;
}
}
}
/*
for (map<string,string>::iterator ip = key.begin(); ip != key.end(); ip++)
cout << ip->first << ":" << ip->second << "\n";
*/
flag = 0;
int count = 0;
cin >> s;
stringstream sss(s);
while (sss >> c) {
// cout << "c:" << c << '\n';
if (!flag) {
if (isalpha(c))
a.push_back(c);
else if (c == ':')
flag = 1;
}
else {
if (isalnum(c))
b.push_back(c);
else {
flag = 0;
// cout << "a:" << a << ", b:" << b << "\n";
if (!key.count(a))
add.insert(a);
else if (key[a] == b)
vis[a] = 1;
else {
cha.insert(a);
vis[a] = 1;
}
a.clear();
b.clear();
if (c == '}')
break;
}
}
}
for (map<string, int>::iterator it = vis.begin(); it != vis.end(); it++)
if (it->second == 0)
rem.insert(it->first);
if (add.empty() && rem.empty() && cha.empty()) {
cout << "No changes\n\n";
continue;
}
if (!add.empty()) {
cout << '+';
disp(add);
}
if (!rem.empty()) {
cout << '-';
disp(rem);
}
if (!cha.empty()) {
cout << '*';
disp(cha);
}
cout << '\n';
}
return 0;
}