uva 12504 Updating a Dictionary

本文介绍了一种通过对比新旧字典来找出增加、减少及修改的词条的算法实现。利用C++编程语言,借助map数据结构存储旧字典中的键值对,并与新字典进行比较。该算法能有效找出不同之处,适用于需要跟踪字典变化的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:Updating a Dictionary


题意:给出一个旧字典和一个新字典,求有旧字典变为新字典增加、减少、修改了那些词条。


思路:

把旧字典key与value的关系用map存起来,和新字典比对。


注意:

1、输出时要注意是每组数据后空一行,而不是两组数据用空行分隔。

2、当字典为空时要讨论。


代码:

#include<cstdio>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;

int main() {

	int T;
	scanf("%d",&T);
	getchar();
	while(T--) {
		map<string,string> mp;
		map<string,bool> Has;
		string x,y;
		getline(cin,x),getline(cin,y);
		string t;
		x[0]=',';
		x[x.size()-1]=',';
		if(x.size()>2)
			for(int i=1; i<x.size(); i++) {
				if(x[i]==',') {
					string one,two;
					int w=t.find(':');
					one=t.substr(0,w);
					two=t.substr(w+1,t.size()-one.size()-1);
					t.clear();
					mp[one]=two;
					Has[one]=false;
				} else {
					t+=x[i];
				}
			}

		vector<string> add,remove,change;

		t.clear();
		y[0]=',';
		y[y.size()-1]=',';
		if(y.size()>2)
			for(int i=1; i<y.size(); i++) {
				if(y[i]==',') {
					string one,two;
					int w=t.find(':');
					one=t.substr(0,w);
					two=t.substr(w+1,t.size()-one.size()-1);
					t.clear();
					if(!mp.count(one)) add.push_back(one);
					else if(mp[one]!=two) change.push_back(one);
					Has[one]=true;
				} else {
					t+=y[i];
				}
			}
		for(map<string,string>::iterator it=mp.begin(); it!=mp.end(); it++) {
			if(Has[it->first]==false) remove.push_back(it->first);
		}


		if(remove.empty()&&add.empty()&&change.empty()) printf("No changes\n");
		if(!add.empty()) {
			sort(add.begin(),add.end());
			printf("+");
			cout<<add[0];
			for(int i=1; i<add.size(); i++) {
				cout<<','<<add[i];
			}
			cout<<endl;
		}
		if(!remove.empty()) {
			sort(remove.begin(),remove.end());
			printf("-");
			cout<<remove[0];
			for(int i=1; i<remove.size(); i++) {
				cout<<','<<remove[i];
			}
			cout<<endl;
		}
		if(!change.empty()) {
			sort(change.begin(),change.end());
			printf("*");
			cout<<change[0];
			for(int i=1; i<change.size(); i++) {
				cout<<','<<change[i];
			}
			cout<<endl;
		}

		printf("\n");
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值