【题目】知识图谱中的实例知识

定义一种简单的知识图谱:

概念:包括父概念及其子概念,通过subClassOf关系联系,父子概念可以有多个层级;

实例:仅和概念之间通过instanceOf关系关联;

关系:通过字符串表示。“student subClassOf person”表示student是person的子概念;“apple instanceOf fruit”表示apple是概念fruit的实例。

编写一个方法。根据概念返回其所有实例(包括子概念的实例;如果没有实例就返回“empty”。

给定的图谱满足:有向图不存在环路;所有点和关系的定义对大小写敏感。

输入第一行为n,取值范围[1,10000],表示图谱中关系的数量。

第2行到第n+1行,每一行表示一组关系。

第n+2行,表示待查找的元节点。

思路:通过哈希表实现概念的快速查找;哈希表的值记录下属的子概念和实例。

#include<iostream>
#include<string>
#include<unordered_map>
#include<vector>
using namespace std;

struct recordNode
{
	vector<string> son;
	vector<string> instance;
};


void findandpr(unordered_map<string, recordNode*> &hash,vector<string>& resr, string refind) {
	if (hash.count(refind)) {
		for (auto x : hash[refind]->instance) {
			resr.push_back(x);
		}
		for (auto y : hash[refind]->son)
			findandpr(hash, resr, y);
	}
	return;
}


int main() {
	int num;
	cin >> num;
	cin.ignore();
	unordered_map<string, recordNode *> hash;
	while (num--) {
		string inputs;
		getline(cin, inputs);
		vector<string> res;
		while (!inputs.empty()) {
			int start = 0;
			if (inputs.find(' ',start) == inputs.npos) {
				res.push_back(inputs);
				break;
			}
			int pos = inputs.find(' ', start);
			string temp = inputs.substr(start, pos);
			inputs.erase(start, pos + 1);
			res.push_back(temp);
		}
		if (res[1] == "subClassOf") {
			if (!hash.count(res[2])) {
				recordNode* re = new recordNode;
				re->son.push_back(res[0]);
				hash.insert(pair<string, recordNode*>(res[2], re));
			}
			else {
				hash[res[2]]->son.push_back(res[0]);
			}
		}
		else {
			if (!hash.count(res[2])) {
				recordNode* re = new recordNode;
				re->instance.push_back(res[0]);
				hash.insert(pair<string, recordNode*>(res[2], re));
			}
			else {
				hash[res[2]]->instance.push_back(res[0]);
			}
		}
	}
	string refind;
	cin >> refind;
	vector<string> resr;
	findandpr(hash, resr, refind);
	for (string x : resr) {
		cout << x << " ";
	}
	cout << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值