跳到正文

个人记录

10.2-2

FzoG约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

思路一

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;

int n, tot, f[N], in[N], a[N], p[N];
string s;

void solve() {
	cin >> n >> s, s = ' ' + s;
	memset(in, 0, sizeof(int) * (n + 5));
	for (int i = 2; i <= n; i++)
		cin >> f[i], in[f[i]]++;
	queue<int> q;
	for (int i = 1; i <= n; i++)
		if (!in[i]) q.push(i), in[i] = -1;
	tot = 0;
	while (!q.empty()) {
		int u = q.front(); q.pop();
		a[++tot] = u, in[f[u]]--;
		if (!in[f[u]]) q.push(f[u]), in[f[u]] = -1;
	}
	tot = 0;
	for (int i = 1; i <= n; i++)
		if (s[i] == 'p') p[a[++tot]] = i;
	for (int i = 1; i <= n; i++)
		if (s[i] != 'p') p[a[++tot]] = i;
	for (int i = 1; i <= n; i++)
		cout << p[i] << " \n"[i == n];
	return;
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	int _; cin >> _;
	while (_--) solve();
    return 0;
}

思路二

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;

int n, tot, f[N], p[N];
string s;
struct node {
	int id, dep;
	bool operator < (const node &x) const {
		return dep > x.dep;
	}
} a[N];

void solve() {
	cin >> n >> s, s = ' ' + s, tot = 0;
	a[1].id = 1, a[1].dep = 1;
	for (int i = 2; i <= n; i++)
		cin >> f[i], a[i].id = i, a[i].dep = a[f[i]].dep + 1;
	sort(a + 1, a + n + 1);
	for (int i = 1; i <= n; i++)
		if (s[i] == 'p') p[a[++tot].id] = i;
	for (int i = 1; i <= n; i++)
		if (s[i] != 'p') p[a[++tot].id] = i;
	for (int i = 1; i <= n; i++)
		cout << p[i] << " ";
	cout<<"\n";
	return;
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	int _; cin >> _;
	while (_--) solve();
    return 0;
}

思路三

C++
#include<bits/stdc++.h>
using namespace std;
#define eb emplace_back
const int N = 1e6 + 10;

int n, tot, f[N], p[N], a[N];
vector<int> adj[N];
string s;

void dfs(int u) {
	for (auto v : adj[u]) dfs(v);
	p[u] = a[++tot];
	return;
}

void solve() {
	cin >> n >> s, s = ' ' + s, tot = 0;
	for (int i = 1; i <= n; i++) adj[i] = vector<int>();
	for (int i = 2; i <= n; i++)
		cin >> f[i], adj[f[i]].eb(i);
	for (int i = 1; i <= n; i++)
		if (s[i] == 'p') a[++tot] = i;
	for (int i = 1; i <= n; i++)
		if (s[i] != 'p') a[++tot] = i;
	tot = 0, dfs(1);
	for (int i = 1; i <= n; i++)
		cout << p[i] << " \n"[i == n];
	return;
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	int _; cin >> _;
	while (_--) solve();
    return 0;
}
原文