栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

codeforces 756 D. Weights Assignment For Tree Edges

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

codeforces 756 D. Weights Assignment For Tree Edges




大致题意:给出每个点的父亲节点编号以及dist排序,问是否能够存在dist值使得上述编号及排序成立

解析:1.由于题目里并没保证这样的树一定存在(可能是多根树),此外还有无解情况就是dist的排序情况,如果根节点排序不是最小的就无解,第二种情况是不只有一个根
2. 对于赋值问题,由于dist[ p i p_i pi​] 所以满足 d i s t [ p i + 1 ] = d i s t [ p i ] + 1 dist[p_i + 1] = dist[p_i]+1 dist[pi​+1]=dist[pi​]+1即可,当前节点到根节点总长度减去父亲到根节点长度即可

#include
using namespace std;
int main()
{
	ios::sync_with_stdio(false);
	int t;
	cin >> t;
	
	while(t --)
	{
		int n;
		cin >> n;
		vector fa(n + 1) , p(n + 1) , dist(n + 1 , -1);
		for (int i = 1; i <= n; ++ i) cin >> fa[i];
		for (int i = 1; i <= n; ++ i) cin >> p[i];
		
		if (fa[p[1]] != p[1])
		{
			cout << -1 << endl;
			continue;
		}
		else
		{
			int ok = 0;
			dist[p[1]] = 0;
			for (int i = 2; i <= n; ++ i)
			{
				if (dist[fa[p[i]]] == -1)
				{
					ok = 1;
					break;
				}
				
				dist[p[i]] = dist[p[i - 1]] + 1;
			}
			
			if (ok)
			{
				cout << -1 << endl;
				continue;
			}
			else 
			{
				for (int i = 1; i <= n; ++ i) cout << dist[i] - dist[fa[i]] << " ";
				cout << endl;	
			}
		}
	}
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号