题目详情 - 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");
}