L2-012 关于堆的判断

 题目详情 - L2-012 关于堆的判断 (pintia.cn)

 为什么对模拟的堆进行down操作24测试点过不了 

而如果对模拟的堆进行up操作却可以过 很奇怪

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int h[N];
int n, m;

int find(int x)
{
	for (int i = 1;i <= n;i++)
	{
		if (h[i] == x)
			return i;
	}
	return 0;
}

void down(int u)
{
	int t = u;
	if (2 * u <= n && h[t] > h[2 * u]) t = 2 * u;
	if (2 * u + 1 <= n && h[t] > h[2 * u + 1]) t = 2 * u + 1;
	if (t != u)
	{
		swap(h[u],h[t]);
		down(t);
	}


}
int main()
{
	cin >> n >> m;
	for (int i = 1;i<=n;i++)
		cin >> h[i];

	for (int i = n/2;i;i--) down(i);
	int x, y;
	string s,s1,s2,s3;
	while (m--)
	{
		cin >> x >> s;
		if (s[0] == 'a')
		{
			cin >> y>>s1>>s2;
			if (find(x) / 2 == find(y) / 2) cout << "T" << endl;
			else cout << "F" << endl;
		}
		else
		{
			cin >> s1 >> s2;
			if (s2[0] == 'r')
			{
				if (find(x) == 1) cout << "T" << endl;
				else cout << "F" << endl;
			}
			else
			{
				cin >> s3 >> y;
				if (s2[0] == 'p')
				{
					if (find(y) / 2 == find(x)) cout << "T" << endl;
					else cout << "F" << endl;
				}
				if (s2[0] == 'c')
				{
					if (find(x) / 2 == find(y)) cout << "T" << endl;
					else cout << "F" << endl;
				}
			}
		}
	}
	for (int i = 1;i <= n;i++)
	{
		cout << h[i] << " " << find(h[i]) << endl;
	}
	system("pause");
}

 

我的代码出来的是上图↑ 下面的代码也就交换了下了孩子节点为什么过不了呢 

求指点!

下图是用up操作的  满分代码里输出的结果

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int h[N];
int n, m;

int find(int x)
{
	for (int i = 1;i <= n;i++)
	{
		if (h[i] == x)
			return i;
	}
	return 0;
}

void up(int u)
{
	while (u / 2 && h[u] < h[u / 2])
	{
		swap(h[u], h[u/2]);
		u >>= 1;
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 1;i <= n;i++)
		cin >> h[i];

	for (int i = 1;i <= n;i++) up(i);
	int x, y;
	string s, s1, s2, s3;
	while (m--)
	{
		cin >> x >> s;
		if (s[0] == 'a')
		{
			cin >> y >> s1 >> s2;
			if (find(x) / 2 == find(y) / 2) cout << "T" << endl;
			else cout << "F" << endl;
		}
		else
		{
			cin >> s1 >> s2;
			if (s2[0] == 'r')
			{
				if (find(x) == 1) cout << "T" << endl;
				else cout << "F" << endl;
			}
			else
			{
				cin >> s3 >> y;
				if (s2[0] == 'p')
				{
					if (find(y) / 2 == find(x)) cout << "T" << endl;
					else cout << "F" << endl;
				}
				if (s2[0] == 'c')
				{
					if (find(x) / 2 == find(y)) cout << "T" << endl;
					else cout << "F" << endl;
				}
			}
		}
	}
	/*for (int i = 1;i <= n;i++)
	{
		cout << h[i] << " " << find(h[i]) << endl;
	}*/
	system("pause");
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值