沐里纷纷


私信TA

用户名:Epoch

访问量:62812

签 名:

我不会算法

等  级
排  名 37
经  验 12816
参赛次数 1
文章发表 172
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

不会算法

解题思路:

并查集吧

为毛超时啊??

最强召唤魔法,地表最强召唤兽~@地表最强召唤兽

注意事项:

参考代码:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>

using namespace std;

map<int, int> dollSet;

int Q(int x)
{
	int ans = 0;
	while (dollSet[x] != x && dollSet[x] != 0)
	{
		x = dollSet[x];
		ans += 1;
	}
	return ans;
}

int P(int x, int n)
{
	int count = 0;
	int preX = x;
	while (dollSet[x] != x && dollSet[x] != 0)
	{	
		//找前驱是x的结点的值,前驱->前驱的前驱 
		for (map<int, int>::iterator it = dollSet.begin(); it != dollSet.end(); it++)
			if (it->second == x)
				it->second = dollSet[x];
		preX = x;
		x = dollSet[x];
		count += 1;
	}
	
	//解开根结点,构造一个虚拟的“根结点” 
	for (map<int, int>::iterator it = dollSet.begin(); it != dollSet.end(); it++)
		if (it->second == n)
			it->second = 0;
			
	return count;
}

int main(void)
{
	int n,m;
	cin >> n >> m;
	for (int i = 1; i <= n - 1; i++)
	{
		int a,b;
		cin >> a >> b;
		dollSet[b] = a;
	}
	dollSet[n] = n;
	
	for (int i = 0; i < m; i++)
	{
		char ch;
		int x;
		cin >> ch >> x;
		switch (ch)
		{
		case 'Q':
			cout << Q(x) << "\n";
			break;
		case 'P':
			cout << P(x, n) << "\n";
			break;
		}
	}
	
    return 0;
}


 

0.0分

5 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区

毒瘤,过了75的测试数据
2019-11-25 10:51:28
dollSet[n] = n;感觉这句没有什么依据,因为节点的标号是从1-n  如果是设置虚拟节点的话,应该是n+1吧
2018-12-15 21:40:37
我也没搞懂这题,想了好久,决定放弃了他,太惨了,我写的方法也是超时的。
2018-12-15 21:17:24
  • «
  • 1
  • »