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

int main() {
    // Fast I/O
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int T;
    cin >> T;
    while(T--) {
        int n;
        cin >> n;
        
        // 1-based indexing: sizes are n + 1
        vector<int> a(n + 1);
        vector<ll> cost(n + 1);
        vector<int> in(n + 1, 0);
        
        // Read 'a' array (1-based)
        for(int i = 1; i <= n; i++) {
            cin >> a[i];
            in[a[i]]++;
        }
        
        // Read 'cost' array (1-based)
        for(int i = 1; i <= n; i++) {
            cin >> cost[i];
        }
        
        queue<int> q;
        vector<int> ans;
        
        // FIXED: Initialize the queue with nodes having in-degree 0
        for(int i = 1; i <= n; i++) {
            if(in[i] == 0) {
                q.push(i);
            }
        }
        
        // Kahn's Algorithm / Topological Sort
        while(!q.empty()){
            int u = q.front();
            q.pop();
            ans.push_back(u);
            
            int v = a[u];
            in[v]--;
            if(in[v] == 0) {
                q.push(v);
            }
        }
        
        // FIXED: Size needs to be n + 1 to support 1-based indexing
        vector<int> vis(n + 1, 0);
        
        for(int i = 1; i <= n; i++){
            if(in[i] == 0 || vis[i]) continue;
            
            vector<int> cycle;
            int cur = i;
            
            while(!vis[cur]){
                vis[cur] = 1;
                cycle.push_back(cur);
                cur = a[cur];
            }
            
            int pos = 0;
            for(int j = 1; j < cycle.size(); j++){
                if(cost[cycle[j]] < cost[cycle[pos]]) {
                    pos = j;
                }
            }
            
            // Push cycle elements so the minimum cost node is placed last
            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 << " ";
        }
        // FIXED: Print a newline after each test case
        cout << "\n";
    }
    return 0;
}