#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;

    while (T--) {

        int n;
        cin >> n;

        vector<int> a(n + 1);
        vector<long long> cost(n + 1);
        vector<int> indeg(n + 1, 0);

        // Read graph
        for (int i = 1; i <= n; i++) {
            cin >> a[i];
            indeg[a[i]]++;
        }

        // Read costs
        for (int i = 1; i <= n; i++)
            cin >> cost[i];

        queue<int> q;
        vector<int> ans;

        // Put all indegree-0 nodes into queue
        for (int i = 1; i <= n; i++) {
            if (indeg[i] == 0)
                q.push(i);
        }

        // Kahn's Algorithm
        while (!q.empty()) {

            int u = q.front();
            q.pop();

            ans.push_back(u);

            int v = a[u];

            indeg[v]--;

            if (indeg[v] == 0)
                q.push(v);
        }

        // Visit remaining cycles
        vector<int> vis(n + 1, 0);

        for (int i = 1; i <= n; i++) {

            // Already removed or already processed
            if (indeg[i] == 0 || vis[i])
                continue;

            vector<int> cycle;

            int cur = i;

            // Walk around the cycle
            while (!vis[cur]) {
                vis[cur] = 1;
                cycle.push_back(cur);
                cur = a[cur];
            }

            // Find minimum-cost node
            int pos = 0;

            for (int j = 1; j < cycle.size(); j++) {
                if (cost[cycle[j]] < cost[cycle[pos]])
                    pos = j;
            }

            // Print after minimum-cost node
            for (int j = pos + 1; j < cycle.size(); j++)
                ans.push_back(cycle[j]);

            for (int j = 0; j <= pos; j++)
                ans.push_back(cycle[j]);
        }

        for (int x : ans)
            cout << x << " ";

        cout << "\n";
    }

    return 0;
}