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

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;
typedef vector<LL> 		VL;
#define si(n) cin>>n
#define dout(n) cout<<n<<"\n"
#define DRT() int t; si(t); while(t--)
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
//# define M_PI           3.14159265358979323846264338327950288

void IO(){
	#ifndef ONLINE_JUDGE
    freopen("../input.txt", "r", stdin);
    freopen("../output.txt", "w", stdout);
	#endif
	srand(chrono::steady_clock::now().time_since_epoch().count());
	off;
}
const int maxn = 100001;
int n,p;
int arr[maxn];
int f(int mid){
	for(int i=0;i<n;i++){
		int diff = max(0, arr[i] - mid);
		if(diff >= (n-i)){
			return 0;
		}
		int choice = n - diff - i;
		int rem = choice % p;
		if(rem == 0){
			return 0;
		}
	}
	return 1;
}
int main(){
	IO();
	cin>>n>>p;
	rep(i,0,n){
		cin>>arr[i];
	}
	sort(arr, arr + n, greater<int> ());
	int s = arr[0] - (n-1);
	{
		// now find the upper limit of the range which satisfy the constraint
		int l = s, h = arr[0]-1;
		int ans = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans = mid;
				l = mid + 1;
			}
			else
				h = mid - 1;
		}
		if(ans == -1){
			cout<<0;
			return 0;
		}
		// now find the lower limit of the range which satisfy the constraint
		l = s, h = ans;
		int ans2 = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans2 = mid;
				h = mid - 1;
			}
			else
				l = mid + 1;
		}

		int cnt = ans - ans2 + 1;
		cout<<cnt<<"\n";
		for(int i=ans2;i<=ans;i++)
			cout<<i<<" ";
	}

	return 0;
}


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

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;
typedef vector<LL> 		VL;
#define si(n) cin>>n
#define dout(n) cout<<n<<"\n"
#define DRT() int t; si(t); while(t--)
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
//# define M_PI           3.14159265358979323846264338327950288

void IO(){
	#ifndef ONLINE_JUDGE
    freopen("../input.txt", "r", stdin);
    freopen("../output.txt", "w", stdout);
	#endif
	srand(chrono::steady_clock::now().time_since_epoch().count());
	off;
}
const int maxn = 100001;
int n,p;
int arr[maxn];
int f(int mid){
	for(int i=0;i<n;i++){
		int diff = max(0, arr[i] - mid);
		if(diff >= (n-i)){
			return 0;
		}
		int choice = n - diff - i;
		int rem = choice % p;
		if(rem == 0){
			return 0;
		}
	}
	return 1;
}
int main(){
	IO();
	cin>>n>>p;
	rep(i,0,n){
		cin>>arr[i];
	}
	sort(arr, arr + n, greater<int> ());

	{
		// now find the upper limit of the range which satisfy the constraint
		int l = 0, h = 1e9;
		int ans = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans = mid;
				l = mid + 1;
			}
			else
				h = mid - 1;
		}
		// now find the lower limit of the range which satisfy the constraint
		l = 0, h = 1e9;
		int ans2 = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans2 = mid;
				h = mid - 1;
			}
			else
				l = mid + 1;
		}
		if(ans == -1)
			cout<<0;
		else{
			int cnt = ans - ans2 + 1;
			cout<<cnt<<"\n";
			for(int i=ans2;i<=ans;i++)
				cout<<i<<" ";
		}
	}

	return 0;
}


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

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;
typedef vector<LL> 		VL;
#define si(n) cin>>n
#define dout(n) cout<<n<<"\n"
#define DRT() int t; si(t); while(t--)
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
//# define M_PI           3.14159265358979323846264338327950288

void IO(){
	#ifndef ONLINE_JUDGE
    freopen("../input.txt", "r", stdin);
    freopen("../output.txt", "w", stdout);
	#endif
	srand(chrono::steady_clock::now().time_since_epoch().count());
	off;
}
const int maxn = 100001;
int n,p;
int arr[maxn];
int f(int mid){
	for(int i=0;i<n;i++){
		int diff = max(0, arr[i] - mid);
		if(diff >= (n-i)){
			return 0;
		}
		int choice = n - diff - i;
		int rem = choice % p;
		if(rem == 0){
			return 0;
		}
	}
	return 1;
}
int main(){
	IO();
	cin>>n>>p;
	rep(i,0,n){
		cin>>arr[i];
	}
	sort(arr, arr + n, greater<int> ());
	int s = arr[0] - (n-1); // minimum value of x for which f(x) > 0 and p does not divide f(x)

	if(f(s)){
		// now find the upper limit of the range which satisfy the constraint
		int l = s, h = 1e9;
		int ans;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans = mid;
				l = mid + 1;
			}
			else
				h = mid - 1;
		}
		int cnt = ans - s + 1;
		cout<<cnt<<"\n";
		for(int i=s;i<=ans;i++)
			cout<<i<<" ";
	}
	else{
		cout<<0;
	}

	return 0;
}


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

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;
typedef vector<LL> 		VL;
#define si(n) cin>>n
#define dout(n) cout<<n<<"\n"
#define DRT() int t; si(t); while(t--)
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
//# define M_PI           3.14159265358979323846264338327950288

void IO(){
	#ifndef ONLINE_JUDGE
    freopen("../input.txt", "r", stdin);
    freopen("../output.txt", "w", stdout);
	#endif
	srand(chrono::steady_clock::now().time_since_epoch().count());
	off;
}
const int maxn = 100001;
int n,p;
int arr[maxn];
int f(int mid){
	for(int i=0;i<n;i++){
		int diff = max(0, arr[i] - mid);
		if(diff >= (n-i)){
			return 0;
		}
		int choice = n - diff - i;
		int rem = choice % p;
		if(rem == 0){
			return 0;
		}
	}
	return 1;
}
int main(){
	IO();
	cin>>n>>p;
	rep(i,0,n){
		cin>>arr[i];
	}
	sort(arr, arr + n, greater<int> ());
	int s = arr[0] - (n);
	{
		// find the upper limit of the range which satisfy the constraint
		int l = s, h = arr[0]-1;
		int ans = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans = mid;
				l = mid + 1;
			}
			else
				h = mid - 1;
		}
		if(ans == -1){
			cout<<0;
			return 0;
		}
		// now find the lower limit of the range which satisfy the constraint
		l = s, h = ans;
		int ans2 = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans2 = mid;
				h = mid - 1;
			}
			else
				l = mid + 1;
		}

		int cnt = ans - ans2 + 1;
		cout<<cnt<<"\n";
		for(int i=ans2;i<=ans;i++)
			cout<<i<<" ";
	}

	return 0;
}


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

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;
typedef vector<LL> 		VL;
#define si(n) cin>>n
#define dout(n) cout<<n<<"\n"
#define DRT() int t; si(t); while(t--)
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
//# define M_PI           3.14159265358979323846264338327950288

void IO(){
	#ifndef ONLINE_JUDGE
    freopen("../input.txt", "r", stdin);
    freopen("../output.txt", "w", stdout);
	#endif
	srand(chrono::steady_clock::now().time_since_epoch().count());
	off;
}
const int maxn = 100001;
int n,p;
int arr[maxn];
int f(int mid){
	for(int i=0;i<n;i++){
		int diff = max(0, arr[i] - mid);
		if(diff >= (n-i)){
			return 0;
		}
		int choice = n - diff - i;
		int rem = choice % p;
		if(rem == 0){
			return 0;
		}
	}
	return 1;
}
int main(){
	IO();
	cin>>n>>p;
	rep(i,0,n){
		cin>>arr[i];
	}
	sort(arr, arr + n, greater<int> ());
	int s = -1;
	rep(i,0,n){
		s = max(s, arr[i] - (n-1-i));
	}
	{
		// find the upper limit of the range which satisfy the constraint
		int l = s, h = arr[0];
		int ans = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			if(f(mid)){
				ans = mid;
				l = mid + 1;
			}
			else
				h = mid - 1;
		}
		if(ans == -1){
			cout<<0;
			return 0;
		}

		int cnt = ans - s + 1;
		cout<<cnt<<"\n";
		for(int i=s;i<=ans;i++)
			cout<<i<<" ";
	}

	return 0;
}


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

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;
typedef vector<LL> 		VL;
#define si(n) cin>>n
#define dout(n) cout<<n<<"\n"
#define DRT() int t; si(t); while(t--)
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
//# define M_PI           3.14159265358979323846264338327950288

void IO(){
	#ifndef ONLINE_JUDGE
    freopen("../input.txt", "r", stdin);
    freopen("../output.txt", "w", stdout);
	#endif
	srand(chrono::steady_clock::now().time_since_epoch().count());
	off;
}
const int maxn = 100001;
int n,p;
int arr[maxn];
int f(int mid){
	for(int i=0;i<n;i++){
		int diff = max(0, arr[i] - mid);
		if(diff >= (n-i)){
			return 0;
		}
		int choice = n - diff - i;
		int rem = choice % p;
		if(rem == 0){
			return 0;
		}
	}
	return 1;
}
int main(){
	IO();
	cin>>n>>p;
	rep(i,0,n){
		cin>>arr[i];
	}
	sort(arr, arr + n, greater<int> ());
	int s = arr[0] - (n-1);
	{
		// now find the upper limit of the range which satisfy the constraint
		int l = s, h = arr[0]-1;
		int ans = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			// cout<<l<<" "<<h<<"\n";
			if(f(mid)){
				ans = mid;
				l = mid + 1;
			}
			else
				h = mid - 1;
		}
		// cout<<"----------\n";
		// now find the lower limit of the range which satisfy the constraint
		l = s, h = arr[0]-1;
		int ans2 = -1;
		while(l <= h){
			int mid = l + (h - l)/2;
			// cout<<l<<" "<<h<<"\n";
			if(f(mid)){
				ans2 = mid;
				h = mid - 1;
			}
			else
				l = mid + 1;
		}
		if(ans == -1 || ans2 == -1)
			cout<<0;
		else{
			int cnt = ans - ans2 + 1;
			cout<<cnt<<"\n";
			for(int i=ans2;i<=ans;i++)
				cout<<i<<" ";
		}
	}

	return 0;
}


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

//.define
// #define FILE_IN_OUT
#define RET(_x)                       return cout << (_x) << '\n', 0;
#define all(_obj)                     (_obj).begin(), (_obj).end()
#define loop(_n)                      for (int i = 0; i < (_n); ++i)
#define CeilDiv(_dividend, _divider)  (((_dividend) - 1LL + (_divider)) / (_divider))
#define sz(_obj)                      static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x)                     std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x)                     {}
#endif
#define endl "\n"
template<typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll  = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<const int>(1e9 + 7);

//.data

//.code
int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin ("input.txt",  std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif

    int n, p;
    cin >> n >> p;
    vector<int> arr(n);
    loop(n) {
        cin >> arr[i];
    }
    sort(all(arr), greater<>());
    const int maxx = arr[0];
    const int minx = maxx - n + 1;
    vector<int> delta(n);
    loop(n) {
        delta[i] = n - i - max(0, arr[i] - minx);
    }
    sort(all(delta));
    vector<int> has(p, 0);
    if (delta[0] > 0) {
        loop(n) {
            ++has[delta[i] % p];
        }
    }
    vector<int> ans;
    for (int x = minx; x < maxx; ++x) {
        int d = x - minx;
        if (delta[0] + d <= 0) {
            continue;
        }
        if (delta[0] <= 0) {
            loop(n) {
                delta[i] += d;
                ++has[delta[i] % p];
            }
        }
        while (!empty(arr) && arr.back() <= x) {
            arr.pop_back();
            --has[delta[sz(arr)] % p];
            ++has[(n - sz(arr)) % p];
        }
        if (n - sz(arr) >= p) {
            break;
        }
        if (has[(p - d % p) % p] > 0) {
            continue;
        }
        ans.push_back(x);
    }
    cout << sz(ans) << endl;
    outarr(all(ans));

#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}


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

//.define
// #define FILE_IN_OUT
#define RET(_x)                       return cout << (_x) << '\n', 0;
#define all(_obj)                     (_obj).begin(), (_obj).end()
#define loop(_n)                      for (int i = 0; i < (_n); ++i)
#define CeilDiv(_dividend, _divider)  (((_dividend) - 1LL + (_divider)) / (_divider))
#define sz(_obj)                      static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x)                     std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x)                     {}
#endif
#define endl "\n"
template<typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll  = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<const int>(1e9 + 7);

//.data

//.code
int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin ("input.txt",  std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif

    int n, p;
    cin >> n >> p;
    vector<int> arr(n);
    loop(n) {
        cin >> arr[i];
    }
    sort(all(arr), greater<>());
    const int maxx = arr[0];
    const int minx = max(arr.back(), maxx - n + 1);
    vector<pii> delta(n);
    loop(n) {
        delta[i].first = n - i - max(0, arr[i] - minx);
        delta[i].second = i;
    }
    sort(all(delta));
    vector<int> ind(n);
    loop(n) {
        ind[delta[i].second] = i;
    }
    vector<int> has(p, 0);
    bool done = false;
    vector<int> ans;
    for (int x = minx; x < maxx; ++x) {
        int d = x - minx;
        if (delta[0].first + d <= 0) {
            continue;
        }
        while (!empty(arr) && arr.back() <= x) {
            arr.pop_back();
            if (done) {
                --has[delta[ind[sz(arr)]].first % p];
            }
        }
        if (n - sz(arr) >= p) {
            break;
        }
        if (!done) {
            loop(sz(arr)) {
                delta[ind[i]].first += d;
                ++has[delta[ind[i]].first % p];
            }
            done = true;
        }
        if (has[(p - d % p) % p] > 0) {
            continue;
        }
        ans.push_back(x);
    }
    cout << sz(ans) << endl;
    outarr(all(ans));

#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}


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

//.define
// #define FILE_IN_OUT
#define RET(_x)                       return cout << (_x) << '\n', 0;
#define all(_obj)                     (_obj).begin(), (_obj).end()
#define loop(_n)                      for (int i = 0; i < (_n); ++i)
#define CeilDiv(_dividend, _divider)  (((_dividend) - 1LL + (_divider)) / (_divider))
#define sz(_obj)                      static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x)                     std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x)                     {}
#endif
#define endl "\n"
template<typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll  = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<const int>(1e9 + 7);

//.data

//.code
int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin ("input.txt",  std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif

    int n, p;
    cin >> n >> p;
    vector<int> arr(n);
    loop(n) {
        cin >> arr[i];
    }
    sort(all(arr), greater<>());
    const int maxx = arr[0];
    const int minx = max(arr.back(), maxx - n + 1);
    vector<int> delta(n);
    loop(n) {
        delta[i] = n - i - max(0, arr[i] - minx);
    }
    sort(all(delta));
    vector<int> has(p, 0);
    bool done = false;
    vector<int> ans;
    for (int x = minx; x < maxx; ++x) {
        int d = x - minx;
        if (delta[0] + d <= 0) {
            continue;
        }
        while (!empty(arr) && arr.back() <= x) {
            arr.pop_back();
            if (done) {
                --has[delta[sz(arr)] % p];
            }
        }
        if (n - sz(arr) >= p) {
            break;
        }
        if (!done) {
            loop(sz(arr)) {
                delta[i] += d;
                ++has[delta[i] % p];
            }
            done = true;
        }
        if (has[(p - d % p) % p] > 0) {
            continue;
        }
        ans.push_back(x);
    }
    cout << sz(ans) << endl;
    outarr(all(ans));

#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}


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

//.define
// #define FILE_IN_OUT
#define RET(_x)                       return cout << (_x) << '\n', 0;
#define all(_obj)                     (_obj).begin(), (_obj).end()
#define loop(_n)                      for (int i = 0; i < (_n); ++i)
#define CeilDiv(_dividend, _divider)  (((_dividend) - 1LL + (_divider)) / (_divider))
#define sz(_obj)                      static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x)                     std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x)                     {}
#endif
#define endl "\n"
template<typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll  = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<const int>(1e9 + 7);

//.data

//.code
int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin ("input.txt",  std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif

    int n, p;
    cin >> n >> p;
    vector<int> arr(n);
    loop(n) {
        cin >> arr[i];
    }
    sort(all(arr), greater<>());
    int maxx = arr[0];
    int minx = max(arr.back(), maxx - n + 1);
    vector<pii> delta(n);
    loop(n) {
        delta[i].first = n - i - max(0, arr[i] - minx);
        delta[i].second = i;
    }
    sort(all(delta));
    vector<int> ind(n);
    loop(n) {
        ind[delta[i].second] = i;
    }
    vector<int> has(p, 0);
    bool done = false;
    vector<int> ans;
    for (int x = minx; x < maxx; ++x) {
        int d = x - minx;
        if (delta[0].first + d <= 0) {
            continue;
        }
        while (arr.back() <= x) {
            arr.pop_back();
            if (done) {
                --has[delta[ind[sz(arr)]].first % p];
            }
        }
        if (n - sz(arr) >= p) {
            break;
        }
        if (!done) {
            minx = x;
            loop(sz(arr)) {
                delta[ind[i]].first += d;
                ++has[delta[ind[i]].first % p];
            }
            done = true;
        }
        if (has[(p - d % p) % p] > 0) {
            continue;
        }
        ans.push_back(x);
    }
    cout << sz(ans) << endl;
    outarr(all(ans));

#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}


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

//.define
// #define FILE_IN_OUT
#define RET(_x)                       return cout << (_x) << '\n', 0;
#define all(_obj)                     (_obj).begin(), (_obj).end()
#define loop(_n)                      for (int i = 0; i < (_n); ++i)
#define CeilDiv(_dividend, _divider)  (((_dividend) - 1LL + (_divider)) / (_divider))
#define sz(_obj)                      static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x)                     std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x)                     {}
#endif
#define endl "\n"
template<typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll  = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<const int>(1e9 + 7);

//.data

//.code
int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin ("input.txt",  std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif

    int n, p;
    cin >> n >> p;
    vector<int> arr(n);
    loop(n) {
        cin >> arr[i];
    }
    sort(all(arr), greater<>());
    const int maxx = arr[0];
    const int minx = maxx - n + 1;
    vector<int> delta(n);
    loop(n) {
        delta[i] = n - i - max(0, arr[i] - minx);
    }
    sort(all(delta));
    vector<int> has(p, 0);
    bool done = false;
    vector<int> ans;
    for (int x = minx; x < maxx; ++x) {
        int d = x - minx;
        if (delta[0] + d <= 0) {
            continue;
        }
        while (!empty(arr) && arr.back() <= x) {
            arr.pop_back();
            if (done) {
                --has[delta[sz(arr)] % p];
            }
        }
        if (n - sz(arr) >= p) {
            break;
        }
        if (!done) {
            loop(sz(arr)) {
                delta[i] += d;
                ++has[delta[i] % p];
            }
            done = true;
        }
        if (has[(p - d % p) % p] > 0) {
            continue;
        }
        ans.push_back(x);
    }
    cout << sz(ans) << endl;
    outarr(all(ans));

#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}


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

//.define
// #define FILE_IN_OUT
#define RET(_x)                       return cout << (_x) << '\n', 0;
#define all(_obj)                     (_obj).begin(), (_obj).end()
#define loop(_n)                      for (int i = 0; i < (_n); ++i)
#define CeilDiv(_dividend, _divider)  (((_dividend) - 1LL + (_divider)) / (_divider))
#define sz(_obj)                      static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x)                     std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x)                     {}
#endif
#define endl "\n"
template<typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll  = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<const int>(1e9 + 7);

//.data

//.code
int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin ("input.txt",  std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif

    int n, p;
    cin >> n >> p;
    vector<int> arr(n);
    loop(n) {
        cin >> arr[i];
    }
    sort(all(arr), greater<>());
    const int maxx = arr[0];
    const int minx = maxx - n + 1;
    vector<int> delta(n);
    loop(n) {
        delta[i] = n - i - max(0, arr[i] - minx);
    }
    sort(all(delta));
    vector<int> has(p, 0);
    if (delta[0] > 0) {
        loop(n) {
            ++has[delta[i] % p];
        }
    }
    vector<int> ans;
    for (int x = minx; x < maxx; ++x) {
        int d = x - minx;
        if (delta[0] + d <= 0) {
            continue;
        }
        if (delta[0] <= 0) {
            loop(n) {
                delta[i] += d;
                ++has[delta[i] % p];
            }
        }
        while (!empty(arr) && arr.back() <= x) {
            arr.pop_back();
            --has[delta[sz(arr)] % p];
        }
        if (n - sz(arr) >= p) {
            break;
        }
        if (has[(p - d % p) % p] > 0) {
            continue;
        }
        ans.push_back(x);
    }
    cout << sz(ans) << endl;
    outarr(all(ans));

#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define INF 0x3f3f3f3f
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
const ll mod=1000000007;
const double PI = acos(-1.0);
const double epsilon = PI / 180.0;//�Ƕ�ת����
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
const int N = 1e5+10;
int n, p;
int a[N];
bool check(int x) {
	ll res = 1;
	int f1 = 0;
	rep(i, 1, n + 1) {
		int id = upper_bound(a + 1, a + 1 + n, x + i - 1) - a - 1;
		if(id - i + 1 <= 0) {
			f1 = 1;
			break;
		}
		res = res * (id - i + 1) % p;
	}
	if(f1 == 1) return false;
	if(res % p) return true;
	return false;
}
int main() {
	cin>>n>>p;
	int t = -1, mn = INF;
	rep(i, 1, n + 1) scanf("%d", &a[i]), t = max(t, a[i]), mn = min(mn, a[i]);
	sort(a + 1, a + 1 + n);
	VI ans;
	int f2 = 0;
	int l = max(t - n + 1, mn), r = t;
	if(!check(l)) {
		cout<<"0\n";
		return 0;
	}
	int st = l;
	while(l < r) {
		int mid = l + r  + 1 >> 1;
		if(check(mid)) l = mid;
		else r = mid - 1;
	}
	int ed = l;
	rep(i, st, ed + 1) ans.pb(i);
	int m = ans.size();
	cout<<m<<"\n";
	rep(i, 0, m) cout<<ans[i]<<" ";
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define INF 0x3f3f3f3f
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
const ll mod=1000000007;
const double PI = acos(-1.0);
const double epsilon = PI / 180.0;//�Ƕ�ת����
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
const int N = 1e5+10;
int n, p;
int a[N];
int check(int x) {
	ll res = 1;
	int f1 = 0;
	rep(i, 1, n + 1) {
		int id = upper_bound(a + 1, a + 1 + n, x + i - 1) - a - 1;
		if(id - i + 1 <= 0) {
			f1 = 1;
			break;
		}
		res = res * (id - i + 1) % p;
	}
	if(f1 == 1) return -1;
	if(res % p) return 1;
	return 0;
}
int main() {
	cin>>n>>p;
	int t = -1, mn = INF;
	rep(i, 1, n + 1) scanf("%d", &a[i]), t = max(t, a[i]), mn = min(mn, a[i]);
	sort(a + 1, a + 1 + n);
	VI ans;
	int f2 = 0;
	int l = max(t - n + 1, mn), r = t;
	while(l < r) {
		int mid = l + r >> 1;
		if(check(mid) != -1) r = mid;
		else l = mid + 1;
	}
	int st = l;
	r = t;
	while(l < r) {
		int mid = l + r  + 1 >> 1;
		if(check(mid)) l = mid;
		else r = mid - 1;
	}
	int ed = l;
	if(st == ed) {
		if(!check(st)) {
			cout<<"0\n";
			return 0;
		}
	}
	rep(i, st, ed + 1) ans.pb(i);
	int m = ans.size();
	cout<<m<<"\n";
	rep(i, 0, m) cout<<ans[i]<<" ";
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define INF 0x3f3f3f3f
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
const ll mod=1000000007;
const double PI = acos(-1.0);
const double epsilon = PI / 180.0;//�Ƕ�ת����
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
const int N = 1e5+10;
int n, p;
int a[N];
bool check(int x) {
	ll res = 1;
	int f1 = 0;
	rep(i, 1, n + 1) {
		int id = upper_bound(a + 1, a + 1 + n, x + i - 1) - a - 1;
		if(id - i + 1 <= 0) {
			f1 = 1;
			break;
		}
		res = res * (id - i + 1) % p;
	}
	if(f1 == 1) return false;
	if(res % p) return true;
	return false;
}
int main() {
	cin>>n>>p;
	int t = -1;
	rep(i, 1, n + 1) scanf("%d", &a[i]), t = max(t, a[i]);
	sort(a + 1, a + 1 + n);
	VI ans;
	int f2 = 0;
	int l = t - n + 1, r = t;
	if(!check(l)) {
		cout<<"0\n";
		return 0;
	}
	int st = l;
	while(l < r) {
		int mid = l + r  + 1 >> 1;
		if(check(mid)) l = mid;
		else r = mid - 1;
	}
	int ed = l;
	rep(i, st, ed + 1) ans.pb(i);
	int m = ans.size();
	cout<<m<<"\n";
	rep(i, 0, m) cout<<ans[i]<<" ";
	return 0;
}


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

vector<string> explode(const string& s, const char& c){
	string buff{""};
	vector<string> v;

	for(auto n:s)
	{
		if(n != c) buff+=n; else
		if(n == c && buff != "") { v.push_back(buff); buff = ""; }
	}
	if(buff != "") v.push_back(buff);

	return v;
}

int check(string s1, string s2){
	string str="!.? ,";
	s1 = " "+s1+" ";
	for(int i=0; i<5; i++){
		for(int j=0; j<5; j++){
			string temp = str[i]+s2+str[j];
			if(s1.find(temp) != string::npos)return 1;
		}
	}
	return 0;
}
int m1[101][101]={0}, mat[101][101]={0};
int arr[110];
int m, n;
vector<string> user;
vector<pair<string,string> > msg;

int solve(int st, int ed, int x){
	if(x == ed+1)return 1;
	if(x-1 >= 0 and m1[x][arr[x-1]] == 1)
		mat[x][arr[x-1]]=0;
	for(int i=0; i<n; i++)
		if(mat[x][i]){
			arr[x] = i;
			if(solve(st, ed, x+1))return 1;
			arr[x] = -1;
		}
	if(x != st and x-1 >= 0 and m1[x][arr[x-1]] == 1)
		mat[x][arr[x-1]] = 1;
	return 0;
}

int main(){
	int t; cin>>t;
	while(t--){
		user.clear();
		msg.clear();
		memset(mat, 0, sizeof(mat));
		memset(m1, 0, sizeof(m1));
		cin>>n;
		for(int i=0; i<n; i++){
			string str="";cin>>str;
			user.push_back(str);
		}
		cin>>m;scanf(" ");

		for(int i=0; i<m; i++){
			string str="";
			getline(cin, str);
			vector<string> v = explode(str, ':');
			msg.push_back({v[0], v[1]});
			if(v[0] == "?"){
				arr[i] = -1;
				for(int j=0; j<n; j++)
					if(!check(v[1], user[j]))
						m1[i][j] = mat[i][j] = 1;
			}
			else{
				for(int j=0; j<n; j++)
					if(v[0] == user[j]){
						arr[i] = j;
						break;
					}
			}
		}
		int flag = 1;
		for(int i=0; i<m; i++){
			if(arr[i] == -1){
				int st = i, ed = i;
				while(ed < m and msg[ed].first == "?")ed++;
				ed--;
				if(ed+1 < m)mat[ed][arr[ed+1]] = 0;
				if(!solve(st, ed, st)){
					flag = 0;
					break;
				}
			}
		}
		if(!flag)cout<<"Impossible\n";
		else{
			for(int i=0; i<m; i++){
				cout<<user[arr[i]]<<":"<<msg[i].second<<endl;
			}
		}
	}
	return 0;
}


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

vector<string> explode(const string& s, const char& c){
	string buff{""};
	vector<string> v;

	for(auto n:s)
	{
		if(n != c) buff+=n; else
		if(n == c && buff != "") { v.push_back(buff); buff = ""; }
	}
	if(buff != "") v.push_back(buff);

	return v;
}

int check(string s1, string s2){
	string str="!.? ,";
	s1 = " "+s1+" ";
	for(int i=0; i<5; i++){
		for(int j=0; j<5; j++){
			string temp = str[i]+s2+str[j];
			if(s1.find(temp) != string::npos)return 1;
		}
	}
	return 0;
}
int m1[101][101]={0}, mat[101][101]={0};
int arr[110];
int m, n;
vector<string> user;
vector<pair<string,string> > msg;
int dp[101][101][101]={0};

/*int solve(int st, int ed, int x){
	if(x == ed+1)return 1;
	if(x-1 >= 0 and m1[x][arr[x-1]] == 1)
		mat[x][arr[x-1]]=0;
	for(int i=0; i<n; i++)
		if(mat[x][i]){
			arr[x] = i;
			if(solve(st, ed, x+1))return 1;
			arr[x] = -1;
		}
	if(x != st and x-1 >= 0 and m1[x][arr[x-1]] == 1)
		mat[x][arr[x-1]] = 1;
	return 0;
}
*/
int main(){
	int t; cin>>t;
	while(t--){
		user.clear();
		msg.clear();
		memset(mat, 0, sizeof(mat));
		memset(dp, 0, sizeof(dp));
		cin>>n;
		for(int i=0; i<n; i++){
			string str="";cin>>str;
			user.push_back(str);
		}
		cin>>m;scanf(" ");

		for(int i=0; i<m; i++){
			string str="";
			getline(cin, str);
			vector<string> v = explode(str, ':');
			msg.push_back({v[0], v[1]});
			if(v[0] == "?"){
				arr[i] = -1;
				for(int j=0; j<n; j++)
					if(!check(v[1], user[j]))
						mat[i][j] = 1;
			}
			else{
				for(int j=0; j<n; j++)
					if(v[0] == user[j]){
						arr[i] = j;
						break;
					}
				mat[i][arr[i]] = 1;
			}
		}
		int flag = 0;

		for(int i=0; i<m; i++){
			if(arr[i] == -1){
				if(i-1 >= 0){
					flag = 0;
					for(int j=0; j<n; j++){
						if(mat[i][j]){

							int chk = 0;
							for(int k=0; k<n; k++){
								if(j != k and mat[i-1][k]){

									for(int l=0; l<i; l++){
										dp[i][j][l] = dp[i-1][k][l];
									}
									dp[i][j][i] = j;
									chk = 1;
									break;
								}
							}
							if(!chk)mat[i][j] = 0;
							flag |= chk;
						}
					}
					if(!flag)break;
				}
				else{
					flag = 0;
					for(int j=0; j<n; j++){
						if(mat[i][j]){
							flag = 1;
							dp[i][j][i] = j;
						}
					}
					if(!flag)break;
				}
			}
			else{
				if(i-1 >= 0){
					flag = 0;
					for(int j=0; j<n; j++){
						if(j!=arr[i] and mat[i-1][j]){
							flag = 1;
							for(int k=0; k<i; k++)
								dp[i][arr[i]][k] = dp[i-1][j][k];
							dp[i][arr[i]][i] = arr[i];
							break;
						}
					}
					if(!flag)break;
				}
				else{
					flag = 1;
					dp[i][arr[i]][i] = arr[i];
				}
			}
		}
		if(!flag)cout<<"Impossible\n";
		else{
			for(int i=0; i<n; i++){
				if(mat[m-1][i]){
					for(int j=0; j<m; j++)
						arr[j] = dp[m-1][i][j];
				}
			}
			for(int i=0; i<m; i++)
				cout<<user[arr[i]]<<":"<<msg[i].second<<endl;
		}
	}
	return 0;
}


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

vector<string> explode(const string& s, const char& c){
	string buff{""};
	vector<string> v;

	for(auto n:s)
	{
		if(n != c) buff+=n; else
		if(n == c && buff != "") { v.push_back(buff); buff = ""; }
	}
	if(buff != "") v.push_back(buff);

	return v;
}

int check(string s1, string s2){
	string str="!.? ,";
	s1 = " "+s1+" ";
	for(int i=0; i<5; i++){
		for(int j=0; j<5; j++){
			string temp = str[i]+s2+str[j];
			if(s1.find(temp) != string::npos)return 1;
		}
	}
	return 0;
}
int mat[101][101]={0};
int arr[110];
int m, n;
vector<string> user;
vector<pair<string,string> > msg;

int solve(int st, int ed, int x){
	if(x == ed+1)return 1;
	if(x-1 >= 0)
		mat[x][arr[x-1]]=0;
	for(int i=0; i<n; i++)
		if(mat[x][i]){
			arr[x] = i;
			if(solve(st, ed, x+1))return 1;
			arr[x] = -1;
		}
	if(x != st and x-1 >= 0)
		mat[x][arr[x-1]] = 1;
	return 0;
}

int main(){
	int t; cin>>t;
	while(t--){
		user.clear();
		msg.clear();
		memset(mat, 0, sizeof(mat));

		cin>>n;
		for(int i=0; i<n; i++){
			string str="";cin>>str;
			user.push_back(str);
		}
		cin>>m;scanf(" ");

		for(int i=0; i<m; i++){
			string str="";
			getline(cin, str);
			vector<string> v = explode(str, ':');
			msg.push_back({v[0], v[1]});
			if(v[0] == "?"){
				arr[i] = -1;
				for(int j=0; j<n; j++)
					if(!check(v[1], user[j]))
						mat[i][j] = 1;
			}
			else{
				for(int j=0; j<n; j++)
					if(v[0] == user[j]){
						arr[i] = j;
						break;
					}
			}
		}
	/*	for(int i=0; i<n; i++)cout<<user[i]<<" ";cout<<endl;
		for(int i=0; i<m; i++)
			cout<<msg[i].first<<" "<<msg[i].second<<endl;
		for(int i=0; i<m; i++){
			for(int j=0; j<n; j++)cout<<mat[i][j]<<" ";
			cout<<endl;
		}*/
		int flag = 1;
		for(int i=0; i<m; i++){
			if(msg[i].first == "?"){
				int st = i, ed = i;
				while(ed < m and msg[ed].first == "?")ed++;
				ed--;
				if(ed+1 < m)mat[ed][arr[ed+1]] = 0;
				if(!solve(st, ed, st)){
					flag = 0;
					break;
				}
			}
		}
		if(!flag)cout<<"Impossible\n";
		else{
			for(int i=0; i<m; i++){
				cout<<user[arr[i]]<<": "<<msg[i].second<<endl;
			}
		}
	}
	return 0;
}


#include <sstream>
#include <fstream>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <utility>
#include <cassert>
#include <bitset>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
#define rFOR(I,S,N) for (I=N;I>=S;I--)

#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define deputs(str) fprintf(stderr, "%s\n",str)
#else
#define debug(...)
#define deputs(str)
#endif // DEBUG
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef long long LL;
typedef long long ll;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=100+7;
const double pi=acos(-1.0);
const double eps=0.00000001;
LL gcd(LL a, LL b) {return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}
template<typename T>inline T powMM(T a, T b) {
    T ret=1;
    for (; b; b>>=1ll,a=(LL)a*a%M)
        if (b&1) ret=(LL)ret*a%M;
    return ret;
}

map<string,int> id;
map<int,string> name;
string A[maxn]; int Bid[maxn];
int pre[maxn][maxn];
int TaskA(){
    int n,m,i,j,k;
    scanf("%d",&n);int tot=0;
    string nowname;
    FOR(i,1,n){
        cin>>nowname;tot++;
        id[nowname]=tot;name[tot]=nowname;
    }scanf("%d",&m); getline(cin,nowname);
    FOR(i,1,m) FOR(j,1,n) pre[i][j]=0;
    FOR(j,1,n) pre[0][j]=n+1;
    FOR(i,1,m){
        string now;
        int pos=0; A[i]="";
        getline(cin,now); nowname="";
        while (pos<now.size()&&now[pos]!=':') {nowname+=now[pos++];}
        A[i]+=now[pos++];//:
        int P=0;
        FOR(j,1,n) if (pre[i-1][j]){
            if (P){
                pre[i][P]=j;
                break;
            }else{
                P=j;
                FOR(k,1,n) if (k!=P) pre[i][k]=P;
            }
        };
        if (id.count(nowname)){
            FOR(k,1,n) if (k!=id[nowname]) pre[i][k]=0;
            while (pos<now.size()) A[i]+=now[pos++];
        }else{
            while (pos<now.size()){
                string text="";
                while (pos<now.size()&&now[pos]!='.'&&now[pos]!=':'&&now[pos]!=','&&now[pos]!='!'&&now[pos]!='?'&&now[pos]!=' '){
                    text+=now[pos];
                    A[i]+=now[pos++];
                }if (id.count(text)) pre[i][id[text]]=0;
                if (pos<now.size()) A[i]+=now[pos++];
            }
        }
    }FOR(j,1,n) if (pre[m][j]){
        for (i=m;i;j=pre[i][j],i--) Bid[i]=j;
        FOR(i,1,m) cout<<name[Bid[i]]+A[i]+'\n';
        return 0;
    }puts("Impossible");
    return 0;
}
void initialize(){}
int main() {
    int startTime=clock();
    //initialize
    initialize();
    debug("/--- initializeTime: %ld milliseconds ---/\n",clock()-startTime);
    int T=1;
    scanf("%d",&T);
    while (T--) TaskA();
}
/*
*/


#include <sstream>
#include <fstream>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <utility>
#include <cassert>
#include <bitset>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
#define rFOR(I,S,N) for (I=N;I>=S;I--)

#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define deputs(str) fprintf(stderr, "%s\n",str)
#else
#define debug(...)
#define deputs(str)
#endif // DEBUG
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef long long LL;
typedef long long ll;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=100+7;
const double pi=acos(-1.0);
const double eps=0.00000001;
LL gcd(LL a, LL b) {return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}
template<typename T>inline T powMM(T a, T b) {
    T ret=1;
    for (; b; b>>=1ll,a=(LL)a*a%M)
        if (b&1) ret=(LL)ret*a%M;
    return ret;
}

map<string,int> id;
map<int,string> name;
string A[maxn]; int Bid[maxn];
int pre[maxn][maxn];
int TaskA(){
    int n,m,i,j,k;
    scanf("%d",&n);int tot=0;
    string nowname;
    FOR(i,1,n){
        cin>>nowname;tot++;
        id[nowname]=tot;name[tot]=nowname;
    }scanf("%d",&m); getline(cin,nowname);
    FOR(i,1,m) FOR(j,1,n) pre[i][j]=0;
    FOR(j,1,n) pre[0][j]=n+1;
    FOR(i,1,m){
        string now;
        int pos=0;
        getline(cin,now); nowname="";
        while (pos<now.size()&&now[pos]!=':') {nowname+=now[pos++];}
        int P=0;
        FOR(j,1,n) if (pre[i-1][j]){
            if (P){
                pre[i][P]=j;
                break;
            }else{
                P=j;
                FOR(k,1,n) if (k!=P) pre[i][k]=P;
            }
        };
        if (id.count(nowname)){
            FOR(k,1,n) if (k!=id[nowname]) pre[i][k]=0;
            while (pos<now.size()) A[i]+=now[pos++];
        }else{
            while (pos<now.size()){
                string text;
                while (pos<now.size()&&now[pos]!='.'&&now[pos]!=','&&now[pos]!='!'&&now[pos]!='?'&&now[pos]!=' '){
                    text+=now[pos];
                    A[i]+=now[pos++];
                }if (id.count(text)) pre[i][id[text]]=0;
                if (pos<now.size()) A[i]+=now[pos++];
            }
        }
    }FOR(j,1,n) if (pre[m][j]){
        for (i=m;i;j=pre[i][j],i--) Bid[i]=j;
        FOR(i,1,m) cout<<name[Bid[i]]+A[i]+'\n';
        return 0;
    }puts("Impossible");
    return 0;
}
void initialize(){}
int main() {
    int startTime=clock();
    //initialize
    initialize();
    debug("/--- initializeTime: %ld milliseconds ---/\n",clock()-startTime);
    int T=1;
    scanf("%d",&T);
    while (T--) TaskA();
}
/*
*/


#include <sstream>
#include <fstream>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <utility>
#include <cassert>
#include <bitset>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
#define rFOR(I,S,N) for (I=N;I>=S;I--)

#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define deputs(str) fprintf(stderr, "%s\n",str)
#else
#define debug(...)
#define deputs(str)
#endif // DEBUG
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef long long LL;
typedef long long ll;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=100+7;
const double pi=acos(-1.0);
const double eps=0.00000001;
LL gcd(LL a, LL b) {return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}
template<typename T>inline T powMM(T a, T b) {
    T ret=1;
    for (; b; b>>=1ll,a=(LL)a*a%M)
        if (b&1) ret=(LL)ret*a%M;
    return ret;
}

map<string,int> id;
map<int,string> name;
string A[maxn]; int Bid[maxn];
int pre[maxn][maxn];
int TaskA(){
    int n,m,i,j,k;
    scanf("%d",&n);int tot=0;
    id.clear();
    string nowname;
    FOR(i,1,n){
        cin>>nowname;tot++;
        id[nowname]=tot;name[tot]=nowname;
    }scanf("%d",&m); getline(cin,nowname);
    FOR(i,1,m) FOR(j,1,n) pre[i][j]=0;
    FOR(j,1,n+1) pre[0][j]=n+1;
    FOR(i,1,m){
        string now;
        int pos=0; A[i]="";
        getline(cin,now); nowname="";
        while (pos<now.size()&&now[pos]!=':') {nowname+=now[pos++];}
        A[i]+=now[pos++];//:
        int P=0;
        FOR(j,1,n+1) if (pre[i-1][j]){
            if (P){
                pre[i][P]=j;
                break;
            }else{
                P=j;
                FOR(k,1,n) if (k!=P) pre[i][k]=P;
            }
        };
        if (id.count(nowname)){
            FOR(k,1,n) if (k!=id[nowname]) pre[i][k]=0;
            while (pos<now.size()) A[i]+=now[pos++];
        }else{
            while (pos<now.size()){
                string text="";
                while (pos<now.size()&&now[pos]!='.'&&now[pos]!=','&&now[pos]!='!'&&now[pos]!='?'&&now[pos]!=' '){
                    text+=now[pos];
                    A[i]+=now[pos++];
                }if (id.count(text)) pre[i][id[text]]=0;
                if (pos<now.size()) A[i]+=now[pos++];
            }
        }
    }FOR(j,1,n) if (pre[m][j]){
        for (i=m;i;j=pre[i][j],i--) Bid[i]=j;
        FOR(i,1,m) cout<<name[Bid[i]]+A[i]+'\n';
        return 0;
    }puts("Impossible");
    return 0;
}
void initialize(){}
int main() {
    int startTime=clock();
    //initialize
    initialize();
    debug("/--- initializeTime: %ld milliseconds ---/\n",clock()-startTime);
    int T=1;
    scanf("%d",&T);
    while (T--) TaskA();
}
/*
1
1
b
1
b:lala!

*/


#include <sstream>
#include <fstream>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <utility>
#include <cassert>
#include <bitset>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
#define rFOR(I,S,N) for (I=N;I>=S;I--)

#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define deputs(str) fprintf(stderr, "%s\n",str)
#else
#define debug(...)
#define deputs(str)
#endif // DEBUG
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef long long LL;
typedef long long ll;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=100+7;
const double pi=acos(-1.0);
const double eps=0.00000001;
LL gcd(LL a, LL b) {return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}
template<typename T>inline T powMM(T a, T b) {
    T ret=1;
    for (; b; b>>=1ll,a=(LL)a*a%M)
        if (b&1) ret=(LL)ret*a%M;
    return ret;
}

map<string,int> id;
map<int,string> name;
string A[maxn]; int Bid[maxn];
int pre[maxn][maxn];
int TaskA(){
    int n,m,i,j,k;
    scanf("%d",&n);int tot=0;
    id.clear();
    string nowname;
    FOR(i,1,n){
        cin>>nowname;tot++;
        id[nowname]=tot;name[tot]=nowname;
    }scanf("%d",&m); getline(cin,nowname);
    FOR(i,1,m) FOR(j,1,n) pre[i][j]=0;
    FOR(i,1,m){
        string now;
        int pos=0; A[i]="";
        getline(cin,now); nowname="";
        while (pos<now.size()&&now[pos]!=':') {nowname+=now[pos++];}
        A[i]+=now[pos++];//:
        int P=0;
        if (i==1) FOR(j,1,n) pre[1][j]=1;
        else{
            FOR(j,1,n) if (pre[i-1][j]){
                if (P){
                    pre[i][P]=j;
                    break;
                }else{
                    P=j;
                    FOR(k,1,n) if (k!=P) pre[i][k]=P;
                }
            };
        }
        if (id.count(nowname)){
            FOR(k,1,n) if (k!=id[nowname]) pre[i][k]=0;
            while (pos<now.size()) A[i]+=now[pos++];
        }else{
            while (pos<now.size()){
                string text="";
                while (pos<now.size()&&now[pos]!='.'&&now[pos]!=','&&now[pos]!='!'&&now[pos]!='?'&&now[pos]!=' '){
                    text+=now[pos];
                    A[i]+=now[pos++];
                }if (id.count(text)) pre[i][id[text]]=0;
                if (pos<now.size()) A[i]+=now[pos++];
            }
        }
    }FOR(j,1,n) if (pre[m][j]){
        for (i=m;i;j=pre[i][j],i--) Bid[i]=j;
        FOR(i,1,m) cout<<name[Bid[i]]+A[i]+'\n';
        return 0;
    }puts("Impossible");
    return 0;
}
void initialize(){}
int main() {
    int startTime=clock();
    //initialize
    initialize();
    debug("/--- initializeTime: %ld milliseconds ---/\n",clock()-startTime);
    int T=1;
    scanf("%d",&T);
    while (T--) TaskA();
}
/*
1
1
b
1
b:lala!

*/


#include <sstream>
#include <fstream>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <utility>
#include <cassert>
#include <bitset>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
#define rFOR(I,S,N) for (I=N;I>=S;I--)

#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define deputs(str) fprintf(stderr, "%s\n",str)
#else
#define debug(...)
#define deputs(str)
#endif // DEBUG
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef long long LL;
typedef long long ll;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=100+7;
const double pi=acos(-1.0);
const double eps=0.00000001;
LL gcd(LL a, LL b) {return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}
template<typename T>inline T powMM(T a, T b) {
    T ret=1;
    for (; b; b>>=1ll,a=(LL)a*a%M)
        if (b&1) ret=(LL)ret*a%M;
    return ret;
}

map<string,int> id;
map<int,string> name;
string A[maxn]; int Bid[maxn];
int pre[maxn][maxn];
int TaskA(){
    int n,m,i,j,k;
    scanf("%d",&n);int tot=0;
    id.clear();
    string nowname;
    FOR(i,1,n){
        cin>>nowname;tot++;
        id[nowname]=tot;name[tot]=nowname;
    }scanf("%d",&m); getline(cin,nowname);
    FOR(i,1,m) FOR(j,1,n) pre[i][j]=0;
    FOR(j,1,n) pre[0][j]=n+1;
    FOR(i,1,m){
        string now;
        int pos=0; A[i]="";
        getline(cin,now); nowname="";
        while (pos<now.size()&&now[pos]!=':') {nowname+=now[pos++];}
        A[i]+=now[pos++];//:
        int P=0;
        FOR(j,1,n) if (pre[i-1][j]){
            if (P){
                pre[i][P]=j;
                break;
            }else{
                P=j;
                FOR(k,1,n) if (k!=P) pre[i][k]=P;
            }
        };
        if (id.count(nowname)){
            FOR(k,1,n) if (k!=id[nowname]) pre[i][k]=0;
            while (pos<now.size()) A[i]+=now[pos++];
        }else{
            while (pos<now.size()){
                string text="";
                while (pos<now.size()&&now[pos]!='.'&&now[pos]!=','&&now[pos]!='!'&&now[pos]!='?'&&now[pos]!=' '){
                    text+=now[pos];
                    A[i]+=now[pos++];
                }if (id.count(text)) pre[i][id[text]]=0;
                if (pos<now.size()) A[i]+=now[pos++];
            }
        }
    }FOR(j,1,n) if (pre[m][j]){
        for (i=m;i;j=pre[i][j],i--) Bid[i]=j;
        FOR(i,1,m) cout<<name[Bid[i]]+A[i]+'\n';
        return 0;
    }puts("Impossible");
    return 0;
}
void initialize(){}
int main() {
    int startTime=clock();
    //initialize
    initialize();
    debug("/--- initializeTime: %ld milliseconds ---/\n",clock()-startTime);
    int T=1;
    scanf("%d",&T);
    while (T--) TaskA();
}
/*
*/


#include <sstream>
#include <fstream>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <utility>
#include <cassert>
#include <bitset>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
#define rFOR(I,S,N) for (I=N;I>=S;I--)

#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define deputs(str) fprintf(stderr, "%s\n",str)
#else
#define debug(...)
#define deputs(str)
#endif // DEBUG
typedef unsigned long long ULL;
typedef unsigned long long ull;
typedef long long LL;
typedef long long ll;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=100+7;
const double pi=acos(-1.0);
const double eps=0.00000001;
LL gcd(LL a, LL b) {return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}
template<typename T>inline T powMM(T a, T b) {
    T ret=1;
    for (; b; b>>=1ll,a=(LL)a*a%M)
        if (b&1) ret=(LL)ret*a%M;
    return ret;
}

map<string,int> id;
map<int,string> name;
string A[maxn]; int Bid[maxn];
int pre[maxn][maxn];
int TaskA(){
    int n,m,i,j,k;
    scanf("%d",&n);int tot=0;
    string nowname;
    FOR(i,1,n){
        cin>>nowname;tot++;
        id[nowname]=tot;name[tot]=nowname;
    }scanf("%d",&m); getline(cin,nowname);
    FOR(i,1,m) FOR(j,1,n) pre[i][j]=0;
    FOR(j,1,n) pre[0][j]=n+1;
    FOR(i,1,m){
        string now;
        int pos=0; A[i]="";
        getline(cin,now); nowname="";
        while (pos<now.size()&&now[pos]!=':') {nowname+=now[pos++];}
        int P=0;
        FOR(j,1,n) if (pre[i-1][j]){
            if (P){
                pre[i][P]=j;
                break;
            }else{
                P=j;
                FOR(k,1,n) if (k!=P) pre[i][k]=P;
            }
        };
        if (id.count(nowname)){
            FOR(k,1,n) if (k!=id[nowname]) pre[i][k]=0;
            while (pos<now.size()) A[i]+=now[pos++];
        }else{
            while (pos<now.size()){
                string text;
                while (pos<now.size()&&now[pos]!='.'&&now[pos]!=','&&now[pos]!='!'&&now[pos]!='?'&&now[pos]!=' '){
                    text+=now[pos];
                    A[i]+=now[pos++];
                }if (id.count(text)) pre[i][id[text]]=0;
                if (pos<now.size()) A[i]+=now[pos++];
            }
        }
    }FOR(j,1,n) if (pre[m][j]){
        for (i=m;i;j=pre[i][j],i--) Bid[i]=j;
        FOR(i,1,m) cout<<name[Bid[i]]+A[i]+'\n';
        return 0;
    }puts("Impossible");
    return 0;
}
void initialize(){}
int main() {
    int startTime=clock();
    //initialize
    initialize();
    debug("/--- initializeTime: %ld milliseconds ---/\n",clock()-startTime);
    int T=1;
    scanf("%d",&T);
    while (T--) TaskA();
}
/*
*/


#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

struct Message
{
    string text;
    set<int> options;

    Message(int n)
    {
        while (n--) {
            options.insert(n);
        }
        text = "";
    }
};

string GetUser(const string &s)
{
    int pos = s.find(":");
    return s.substr(0, pos);
}

bool Back(const vector<Message> &mess, const vector<int> &pos,
          int lev, vector<int> st)
{
    int index = pos[lev];
    for (int opt : mess[index].options) {
        if (lev > 0 && pos[lev - 1] == index - 1) {
            if (opt == st[lev - 1]) {
                continue;
            }
        }

        st[lev] = opt;
        if (lev + 1 == pos.size()) {
            return true;
        } else if (Back(mess, pos, lev + 1, st)) {
            return true;
        }
    }
    return false;
}

bool FindSolution(vector<Message> &mess, const vector<int> &pos)
{
    vector<int> st(pos.size());
    bool found = Back(mess, pos, 0, st);

    if (found) {
        for (unsigned i = 0; i < st.size(); ++i) {
            mess[pos[i]].options.clear();
            mess[pos[i]].options.insert(st[i]);
        }
    }
    return found;
}

void Strip(string &s)
{
    static const string punc = ",:.!?";

    while (s[0] != ':') {
        s.erase(s.begin());
    }

    for (char &c : s) {
        if (punc.find(c) != string::npos) {
            c = ' ';
        }
    }
    s += " ";
}

vector<int> FindUsers(const string &s, const map<string, int> &ni)
{
    string clean(s);
    Strip(clean);

    vector<int> users;
    int orig = 0;
    int pos = clean.find(" ");
    while (pos != string::npos) {
        string sub = clean.substr(orig, pos - orig);
        auto it = ni.find(sub);
        if (it != ni.end()) {
            users.push_back(it->second);
        }

        orig = pos + 1;
        pos = clean.find(" ", pos + 1);
    }

    return users;
}

int main()
{
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        vector<string> names(n);
        map<string, int> name_index;
        for (int i = 0; i < n; ++i) {
            cin >> names[i];
            name_index[names[i]] = i;
        }

        int m;
        cin >> m;
        cin.get();

        vector<Message> mess;
        for (int i = 0; i < m; ++i) {
            auto curr_mess = Message(n);
            getline(cin, curr_mess.text);

            auto user = GetUser(curr_mess.text);
            if (user != "?") {
                curr_mess.options.clear();
                curr_mess.options.insert(name_index[user]);
                if (!mess.empty()) {
                    mess.back().options.erase(name_index[user]);
                }
            } else {
                auto users = FindUsers(curr_mess.text, name_index);
                for (int ind : users) {
                    curr_mess.options.erase(ind);
                }
            }

            if (!mess.empty() && mess.back().options.size() == 1) {
                auto other_user = *mess.back().options.begin();
                curr_mess.options.erase(other_user);
            }

            mess.push_back(curr_mess);
        }

        vector<int> pending;
        bool valid = true;
        for (int i = 0; i < m; ++i) {
            if (mess[i].options.size() > 1) {
                pending.push_back(i);
            } else if (mess[i].options.size() == 0) {
                valid = false;
                break;
            }
        }

        if (pending.size() > 0 && valid) {
            valid = FindSolution(mess, pending);
        }

        if (!valid) {
            cout << "Impossible\n";
        } else {
            for (auto &m : mess) {
                int index = *m.options.begin();
                if (m.text[0] == '?') {
                    m.text.replace(0, 1, names[index]);
                }
                cout << m.text << "\n";
            }
        }
    }
    return 0;
}


#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

struct Message
{
    bool solved;
    set<int> users;
    string text;
};

string FindUser(const string &s)
{
    int pos = s.find(":");
    return s.substr(0, pos);
}

void Strip(string &s)
{
    const string sep = ".,!?";
    while (sep.find(s[0]) != string::npos || s[0] == ' ')
        s.erase(s.begin());

    for (char &c : s)
        if (sep.find(c) != string::npos)
            c = ' ';
    s += " ";
}

int main()
{
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        map<string, int> name_index;
        vector<string> names(n);
        for (int i = 0; i < n; ++i) {
            cin >> names[i];
            name_index.insert({ names[i], i });
        }

        int m;
        cin >> m;
        cin.get();

        vector<Message> messages(m);
        for (auto &mes : messages) {
            mes.solved = false;
            for (int i = 0; i < n; ++i)
                mes.users.insert(i);
        }

        int solved = 0;
        for (int i = 0; i < m; ++i) {
            getline(cin, messages[i].text);
            string user = FindUser(messages[i].text);

            if (user != "?") {
                int index = name_index[user];
                messages[i].users.insert(index);
                messages[i].solved = true;
                ++solved;
                if (i > 0 && !messages[i - 1].solved)
                    messages[i - 1].users.erase(index);
                if (i < m - 1)
                    messages[i + 1].users.erase(index);
            }

            string mess = messages[i].text.substr(messages[i].text.find(":") + 1);
            Strip(mess);

            int orig = 0;
            int pos = mess.find(" ");
            while (pos != string::npos) {
                auto it = name_index.find(mess.substr(orig, pos - orig));
                if (it != name_index.end())
                    messages[i].users.erase(it->second);
                orig = pos + 1;
                pos = mess.find(" ", pos + 1);
            }
        }

        bool valid = true;
        while (solved < n) {
            bool change = false;
            for (int i = 0; i < m; ++i) {
                if (!messages[i].solved && messages[i].users.size() == 1) {
                    change = true;
                    int index = *messages[i].users.begin();
                    if (i > 0 && !messages[i - 1].solved)
                        messages[i - 1].users.erase(index);
                    if (i < m - 1 && !messages[i + 1].solved)
                        messages[i + 1].users.erase(index);
                    messages[i].solved = true;
                    ++solved;
                }
            }
            if (!change) {
                valid = false;
                break;
            }
        }

        if (!valid) {
            cout << "Impossible\n";
            continue;
        }

        for (const auto &line : messages) {
            if (line.text[0] == '?')
                cout << names[*line.users.begin()] + line.text.substr(1) << "\n";
            else cout << line.text << "\n";
        }
    }
    return 0;
}


#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

struct Message
{
    string text;
    set<int> options;

    Message(int n)
    {
        while (n--) {
            options.insert(n);
        }
        text = "";
    }
};

string GetUser(const string &s)
{
    int pos = s.find(":");
    return s.substr(0, pos);
}

bool Back(const vector<Message> &mess, const vector<int> &pos,
    int lev, vector<int> &st)
{
    int index = pos[lev];
    for (int opt : mess[index].options) {
        if (lev > 0 && pos[lev - 1] == index - 1) {
            if (opt == st[lev - 1]) {
                continue;
            }
        }

        st[lev] = opt;
        if (lev + 1 == pos.size()) {
            return true;
        }
        else if (Back(mess, pos, lev + 1, st)) {
            return true;
        }
    }
    return false;
}

bool FindSolution(vector<Message> &mess, const vector<int> &pos)
{
    vector<int> st(pos.size());
    bool found = Back(mess, pos, 0, st);

    if (found) {
        for (unsigned i = 0; i < st.size(); ++i) {
            mess[pos[i]].options.clear();
            mess[pos[i]].options.insert(st[i]);
        }
    }
    return found;
}

void Strip(string &s)
{
    static const string punc = ",:.!?";

    while (s[0] != ':') {
        s.erase(s.begin());
    }

    for (char &c : s) {
        if (punc.find(c) != string::npos) {
            c = ' ';
        }
    }
    s += " ";
}

vector<int> FindUsers(const string &s, const map<string, int> &ni)
{
    string clean(s);
    Strip(clean);

    vector<int> users;
    int orig = 0;
    int pos = clean.find(" ");
    while (pos != string::npos) {
        string sub = clean.substr(orig, pos - orig);
        auto it = ni.find(sub);
        if (it != ni.end()) {
            users.push_back(it->second);
        }

        orig = pos + 1;
        pos = clean.find(" ", pos + 1);
    }

    return users;
}

int main()
{
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        vector<string> names(n);
        map<string, int> name_index;
        for (int i = 0; i < n; ++i) {
            cin >> names[i];
            name_index[names[i]] = i;
        }

        int m;
        cin >> m;
        cin.get();

        vector<Message> mess;
        for (int i = 0; i < m; ++i) {
            auto curr_mess = Message(n);
            getline(cin, curr_mess.text);

            auto user = GetUser(curr_mess.text);
            if (user != "?") {
                curr_mess.options.clear();
                curr_mess.options.insert(name_index[user]);
                if (!mess.empty()) {
                    mess.back().options.erase(name_index[user]);
                }
            }
            else {
                auto users = FindUsers(curr_mess.text, name_index);
                for (int ind : users) {
                    curr_mess.options.erase(ind);
                }
            }

            if (!mess.empty() && mess.back().options.size() == 1) {
                auto other_user = *mess.back().options.begin();
                curr_mess.options.erase(other_user);
            }

            mess.push_back(curr_mess);
        }

        vector<int> pending;
        bool valid = true;
        for (int i = 0; i < m; ++i) {
            if (mess[i].options.size() > 1) {
                pending.push_back(i);
            }
            else if (mess[i].options.size() == 0) {
                valid = false;
                break;
            }
        }

        if (pending.size() > 0 && valid) {
            valid = FindSolution(mess, pending);
        }

        if (!valid) {
            cout << "Impossible\n";
        }
        else {
            for (auto &m : mess) {
                int index = *m.options.begin();
                if (m.text[0] == '?') {
                    m.text.replace(0, 1, names[index]);
                }
                cout << m.text << "\n";
            }
        }
    }
    return 0;
}


#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

struct Message
{
    string text;
    set<int> options;

    Message(int n)
    {
        while (n--) {
            options.insert(n);
        }
        text = "";
    }
};

string GetUser(const string &s)
{
    int pos = s.find(":");
    return s.substr(0, pos);
}

bool Back(const vector<Message> &mess, const vector<int> &pos,
          int lev, vector<int> st)
{
    for (int opt : mess[pos[lev]].options) {
        int index = pos[lev];
        if (lev > 0 && pos[lev - 1] == index - 1) {
            if (opt == st[lev - 1]) {
                continue;
            }
        }

        st[lev] = opt;
        if (lev + 1 == pos.size()) {
            return true;
        } else if (Back(mess, pos, lev + 1, st)) {
            return true;
        }
    }
    return false;
}

bool FindSolution(vector<Message> &mess, const vector<int> &pos)
{
    vector<int> st(pos.size());
    bool found = Back(mess, pos, 0, st);

    if (found) {
        for (unsigned i = 0; i < st.size(); ++i) {
            mess[pos[i]].options.clear();
            mess[pos[i]].options.insert(st[i]);
        }
    }
    return found;
}

void Strip(string &s)
{
    static const string punc = ",:.!?";
    for (char &c : s) {
        if (punc.find(c) != string::npos) {
            c = ' ';
        }
    }
    s += " ";
}

vector<int> FindUsers(const string &s, const map<string, int> &ni)
{
    string clean(s);
    Strip(clean);

    vector<int> users;
    int orig = 0;
    int pos = clean.find(" ");
    while (pos != string::npos) {
        string sub = clean.substr(orig, pos - orig);
        auto it = ni.find(sub);
        if (it != ni.end()) {
            users.push_back(it->second);
        }

        orig = pos + 1;
        pos = clean.find(" ", pos + 1);
    }

    return users;
}

int main()
{
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        vector<string> names(n);
        map<string, int> name_index;
        for (int i = 0; i < n; ++i) {
            cin >> names[i];
            name_index[names[i]] = i;
        }

        int m;
        cin >> m;
        cin.get();

        vector<Message> mess;
        for (int i = 0; i < m; ++i) {
            auto curr_mess = Message(n);
            getline(cin, curr_mess.text);

            auto user = GetUser(curr_mess.text);
            if (user != "?") {
                curr_mess.options.clear();
                curr_mess.options.insert(name_index[user]);
                if (!mess.empty()) {
                    mess.back().options.erase(name_index[user]);
                }
            } else {
                auto users = FindUsers(curr_mess.text, name_index);
                for (int ind : users) {
                    curr_mess.options.erase(ind);
                }
            }

            if (!mess.empty() && mess.back().options.size() == 1) {
                auto other_user = *mess.back().options.begin();
                curr_mess.options.erase(other_user);
            }

            mess.push_back(curr_mess);
        }

        vector<int> pending;
        bool valid = true;
        for (int i = 0; i < m; ++i) {
            if (mess[i].options.size() > 1) {
                pending.push_back(i);
            } else if (mess[i].options.size() == 0) {
                valid = false;
                break;
            }
        }

        if (pending.size() > 0 && valid) {
            valid = FindSolution(mess, pending);
        }

        if (!valid) {
            cout << "Impossible\n";
        } else {
            for (auto &m : mess) {
                int index = *m.options.begin();
                if (m.text[0] == '?') {
                    m.text.replace(0, 1, names[index]);
                }
                cout << m.text << "\n";
            }
        }
    }
    return 0;
}


#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

struct Message
{
    string text;
    set<int> options;

    Message(int n)
    {
        while (n--) {
            options.insert(n);
        }
        text = "";
    }
};

string GetUser(const string &s)
{
    int pos = s.find(":");
    return s.substr(0, pos);
}

bool Back(const vector<Message> &mess, int lev, vector<int> &st)
{
    for (int opt : mess[lev].options) {
        if (lev > 0 && st[lev - 1] == opt) {
            continue;
        }

        st[lev] = opt;
        if (lev + 1 == mess.size()) {
            return true;
        }
        else if (Back(mess, lev + 1, st)) {
            return true;
        }
    }
    return false;
}

bool FindSolution(vector<Message> &mess)
{
    vector<int> st(mess.size());
    bool found = Back(mess, 0, st);

    if (found) {
        for (unsigned i = 0; i < st.size(); ++i) {
            mess[i].options.clear();
            mess[i].options.insert(st[i]);
        }
    }
    return found;
}

void Strip(string &s)
{
    static const string punc = ",:.!?";

    while (s[0] != ':') {
        s.erase(s.begin());
    }

    for (char &c : s) {
        if (punc.find(c) != string::npos) {
            c = ' ';
        }
    }
    s += " ";
}

vector<int> FindUsers(const string &s, const map<string, int> &ni)
{
    string clean(s);
    Strip(clean);

    vector<int> users;
    int orig = 0;
    int pos = clean.find(" ");
    while (pos != string::npos) {
        string sub = clean.substr(orig, pos - orig);
        auto it = ni.find(sub);
        if (it != ni.end()) {
            users.push_back(it->second);
        }

        orig = pos + 1;
        pos = clean.find(" ", pos + 1);
    }

    return users;
}

int main()
{
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        vector<string> names(n);
        map<string, int> name_index;
        for (int i = 0; i < n; ++i) {
            cin >> names[i];
            name_index[names[i]] = i;
        }

        int m;
        cin >> m;
        cin.get();

        vector<Message> mess;
        for (int i = 0; i < m; ++i) {
            auto curr_mess = Message(n);
            getline(cin, curr_mess.text);

            auto user = GetUser(curr_mess.text);
            if (user != "?") {
                curr_mess.options.clear();
                curr_mess.options.insert(name_index[user]);
                if (!mess.empty()) {
                    mess.back().options.erase(name_index[user]);
                }
            }
            else {
                auto users = FindUsers(curr_mess.text, name_index);
                for (int ind : users) {
                    curr_mess.options.erase(ind);
                }
            }

            if (!mess.empty() && mess.back().options.size() == 1) {
                auto other_user = *mess.back().options.begin();
                curr_mess.options.erase(other_user);
            }

            mess.push_back(curr_mess);
        }

        int pending = 0;
        bool valid = true;
        for (int i = 0; i < m; ++i) {
            if (mess[i].options.size() > 1) {
                ++pending;
            }
            else if (mess[i].options.size() == 0) {
                valid = false;
                break;
            }
        }

        if (pending > 0 && valid) {
            valid = FindSolution(mess);
        }

        if (!valid) {
            cout << "Impossible\n";
        }
        else {
            for (auto &m : mess) {
                int index = *m.options.begin();
                if (m.text[0] == '?') {
                    m.text.replace(0, 1, names[index]);
                }
                cout << m.text << "\n";
            }
        }
    }
    return 0;
}


// written at 20:24 on 17 Jan 2017
#include <bits/stdc++.h>

#define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);
// #define __DEBUG__
#ifdef __DEBUG__
	#define DEBUG(...) printf(__VA_ARGS__)
#else
	#define DEBUG(...)
#endif
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout);
#define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans");
#define rep(i, j, k) for (int i = j; i < k; ++i)
#define irep(i, j, k) for (int i = j - 1; i >= k; --i)

using namespace std;

template <typename T>
inline T sqr(T a) { return a * a;};

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int > Pii;
const double pi = acos(-1.0);
const int INF = INT_MAX;
const int MAX_N = 1e2 + 10;
const int MAX_M = 1e2 + 10;
int t, N, M, pre[MAX_M][MAX_N];
bool dp[MAX_M][MAX_N];
string name[MAX_N], sentence[MAX_M], s;

void write(int i, int j) {
	if (!i) return;
	write(i - 1, pre[i][j]);
	if (sentence[i - 1][0] != '?')
		cout << sentence[i - 1] << endl;
	else {
		cout << name[j];
		string s(sentence[i - 1], sentence[i - 1].find(':'), string::npos);
		cout << s << endl;
	}
}
bool in(string s, string S) {
	rep(i, 0, S.size())
		if (!isalnum(S[i])) S[i] = ' ';
	S = S + " ";
	return	S.find(" " + s + " ") != string::npos;
}
void solve() {
	memset(dp, false, sizeof dp);
	memset(pre, -1, sizeof pre);
	rep(i, 0, N) dp[0][i] = true;
	rep(i, 0, M) if (sentence[i][0] == '?') {
		rep(j, 0, N) if (!in(name[j], sentence[i])) {
			rep(k, 0, N) if (k != j && dp[i][k]) {
				dp[i + 1][j] = true;
				pre[i + 1][j] = k;
				break;
			}
		}
	} else {
        int id = -1;
        string s(sentence[i], 0, sentence[i].find(':'));
		rep(j, 0, N) if (s == name[j]) {id = j; break;}
		rep(j, 0, N) if (j != id && dp[i][j]) {
			dp[i + 1][id] = true;
			pre[i + 1][id] = j;
			break;
		}
	}
	rep(i, 0, N)
		if (dp[M][i]) {
			write(M, i);
			return;
		}
	cout << "Impossible" << endl;
}

int main(int argc, char const *argv[])
{
	IOS;
	cin >> t;
	rep(i, 0, t) {
		cin >> N; getline(cin, s);
		rep(i, 0, N)
			cin >> name[i];
		cin >> M; getline(cin, s);
		rep(i, 0, M)
			getline(cin, sentence[i]);
		solve();
	}
	return 0;
}


// written at 20:24 on 17 Jan 2017
#include <bits/stdc++.h>

#define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);
// #define __DEBUG__
#ifdef __DEBUG__
	#define DEBUG(...) printf(__VA_ARGS__)
#else
	#define DEBUG(...)
#endif
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout);
#define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans");
#define rep(i, j, k) for (int i = j; i < k; ++i)
#define irep(i, j, k) for (int i = j - 1; i >= k; --i)

using namespace std;

template <typename T>
inline T sqr(T a) { return a * a;};

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int > Pii;
const double pi = acos(-1.0);
const int INF = INT_MAX;
const int MAX_N = 1e2 + 10;
const int MAX_M = 1e2 + 10;
int t, N, M, pre[MAX_M][MAX_N];
bool dp[MAX_M][MAX_N];
string name[MAX_N], sentence[MAX_M], s;

void write(int i, int j) {
	if (!i) return;
	write(i - 1, pre[i][j]);
	if (sentence[i - 1][0] != '?')
		cout << sentence[i - 1] << endl;
	else {
		cout << name[j];
		string s(sentence[i - 1], sentence[i - 1].find(':'), string::npos);
		cout << s << endl;
	}
}
bool in(string s, string S) {
	rep(i, 0, S.size())
		if (!isalnum(S[i]) && S[i] != ':' && i) S[i] = ' ';
	S = " " + S + " ";
	return	S.find(" " + s + " ") != string::npos;
}
void solve() {
	memset(dp, false, sizeof dp);
	memset(pre, -1, sizeof pre);
	rep(i, 0, N) dp[0][i] = true;
	rep(i, 0, M) if (sentence[i][0] == '?') {
		rep(j, 0, N) if (!in(name[j], sentence[i])) {
			rep(k, 0, N) if (k != j && dp[i][k]) {
				dp[i + 1][j] = true;
				pre[i + 1][j] = k;
				break;
			}
		}
	} else {
        int id = -1;
        string s(sentence[i], 0, sentence[i].find(':'));
		rep(j, 0, N) if (s == name[j]) {id = j; break;}
		rep(j, 0, N) if (j != id && dp[i][j]) {
			dp[i + 1][id] = true;
			pre[i + 1][id] = j;
			break;
		}
	}
	rep(i, 0, N)
		if (dp[M][i]) {
			write(M, i);
			return;
		}
	cout << "Impossible" << endl;
}

int main(int argc, char const *argv[])
{
	IOS;
	cin >> t;
	rep(i, 0, t) {
		cin >> N; getline(cin, s);
		rep(i, 0, N)
			cin >> name[i];
		cin >> M; getline(cin, s);
		rep(i, 0, M)
			getline(cin, sentence[i]);
		solve();
	}
	return 0;
}


// written at 20:24 on 17 Jan 2017
#include <bits/stdc++.h>

#define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);
// #define __DEBUG__
#ifdef __DEBUG__
	#define DEBUG(...) printf(__VA_ARGS__)
#else
	#define DEBUG(...)
#endif
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout);
#define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans");
#define rep(i, j, k) for (int i = j; i < k; ++i)
#define irep(i, j, k) for (int i = j - 1; i >= k; --i)

using namespace std;

template <typename T>
inline T sqr(T a) { return a * a;};

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int > Pii;

const double pi = acos(-1.0);
const int INF = INT_MAX;
const int MAX_N = 1e2 + 10;
const int MAX_M = 1e2 + 10;

int t, N, M, pre[MAX_M][MAX_N];
bool dp[MAX_M][MAX_N];
string name[MAX_N], sentence[MAX_M];

void write(int i, int j) {
	if (!i) return;
	write(i - 1, pre[i][j]);
	if (sentence[i - 1][0] != '?')
		cout << sentence[i - 1] << endl;
	else {
		cout << name[j];
		string s(sentence[i - 1], sentence[i - 1].find(':'), string::npos);
		cout << s << endl;
	}
}
void solve() {
	memset(dp, false, sizeof dp);
	memset(pre, -1, sizeof pre);
	rep(i, 0, N) dp[0][i] = true;
	rep(i, 0, M) if (sentence[i][0] == '?') {
		rep(j, 0, N) if (sentence[i].find(name[j]) == string::npos) {
			rep(k, 0, N) if (k != j && dp[i][k]) {
				dp[i + 1][j] = true;
				pre[i + 1][j] = k;
				break;
			}
		}
	} else {
        int id = -1;
        string s(sentence[i], 0, sentence[i].find(':'));
		rep(j, 0, N) if (s == name[j]) {id = j; break;}
		rep(j, 0, N) if (j != id && dp[i][j]) {
			dp[i + 1][id] = true;
			pre[i + 1][id] = j;
			break;
		}
	}
	rep(i, 0, N)
		if (dp[M][i]) {
			write(M, i);
			return;
		}
	printf("Impossible\n");
}

int main(int argc, char const *argv[])
{
	scanf("%d", &t);
	rep(i, 0, t) {
		scanf("%d", &N);
		rep(i, 0, N)
			cin >> name[i];
		scanf("%d", &M);
		getline(cin, sentence[0]);
		rep(i, 0, M)
			getline(cin, sentence[i]);
		solve();
	}
	return 0;
}


// written at 20:24 on 17 Jan 2017
#include <bits/stdc++.h>

#define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);
// #define __DEBUG__
#ifdef __DEBUG__
	#define DEBUG(...) printf(__VA_ARGS__)
#else
	#define DEBUG(...)
#endif
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout);
#define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans");
#define rep(i, j, k) for (int i = j; i < k; ++i)
#define irep(i, j, k) for (int i = j - 1; i >= k; --i)

using namespace std;

template <typename T>
inline T sqr(T a) { return a * a;};

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int > Pii;
const double pi = acos(-1.0);
const int INF = INT_MAX;
const int MAX_N = 1e2 + 10;
const int MAX_M = 1e2 + 10;
int t, N, M, pre[MAX_M][MAX_N];
bool dp[MAX_M][MAX_N];
string name[MAX_N], sentence[MAX_M], s;

void write(int i, int j) {
	if (!i) return;
	write(i - 1, pre[i][j]);
	if (sentence[i - 1][0] != '?')
		cout << sentence[i - 1] << endl;
	else {
		cout << name[j];
		string s(sentence[i - 1], sentence[i - 1].find(':'), string::npos);
		cout << s << endl;
	}
}
bool in(string s, string S) {
	rep(i, 0, S.size())
		if (!isalnum(S[i])) S[i] = ' ';
	S = S + " ";
	return	S.find(" " + s + " ") != string::npos;
}
void solve() {
	memset(dp, false, sizeof dp);
	memset(pre, -1, sizeof pre);
	rep(i, 0, N) dp[0][i] = true;
	rep(i, 0, M) if (sentence[i][0] == '?') {
		rep(j, 0, N) if (!in(name[j], sentence[i])) {
			rep(k, 0, N) if (k != j && dp[i][k]) {
				dp[i + 1][j] = true;
				pre[i + 1][j] = k;
				break;
			}
		}
	} else {
        int id = -1;
        string s(sentence[i], 0, sentence[i].find(':'));
		rep(j, 0, N) if (s == name[j]) {id = j; break;}
		rep(j, 0, N) if ((j != id || !i) && dp[i][j]) {
			dp[i + 1][id] = true;
			pre[i + 1][id] = j;
			break;
		}
	}
	rep(i, 0, N)
		if (dp[M][i]) {
			write(M, i);
			return;
		}
	cout << "Impossible" << endl;
}

int main(int argc, char const *argv[])
{
	IOS;
	cin >> t;
	rep(i, 0, t) {
		cin >> N; getline(cin, s);
		rep(i, 0, N)
			cin >> name[i];
		cin >> M; getline(cin, s);
		rep(i, 0, M)
			getline(cin, sentence[i]);
		solve();
	}
	return 0;
}


// written at 20:24 on 17 Jan 2017
#include <bits/stdc++.h>

#define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);
// #define __DEBUG__
#ifdef __DEBUG__
	#define DEBUG(...) printf(__VA_ARGS__)
#else
	#define DEBUG(...)
#endif
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout);
#define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans");
#define rep(i, j, k) for (int i = j; i < k; ++i)
#define irep(i, j, k) for (int i = j - 1; i >= k; --i)

using namespace std;

template <typename T>
inline T sqr(T a) { return a * a;};

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int > Pii;
const double pi = acos(-1.0);
const int INF = INT_MAX;
const int MAX_N = 1e2 + 10;
const int MAX_M = 1e2 + 10;
int t, N, M, pre[MAX_M][MAX_N];
bool dp[MAX_M][MAX_N];
string name[MAX_N], sentence[MAX_M], s;

void write(int i, int j) {
	if (!i) return;
	write(i - 1, pre[i][j]);
	if (sentence[i - 1][0] != '?')
		cout << sentence[i - 1] << endl;
	else {
		cout << name[j];
		string s(sentence[i - 1], sentence[i - 1].find(':'), string::npos);
		cout << s << endl;
	}
}
bool in(string s, string S) {
	rep(i, 0, S.size())
		if (!isalnum(S[i]) && S[i] != ':' && i) S[i] = ' ';
	return	S.find(" " + s + " ") != string::npos;
}
void solve() {
	memset(dp, false, sizeof dp);
	memset(pre, -1, sizeof pre);
	rep(i, 0, N) dp[0][i] = true;
	rep(i, 0, M) if (sentence[i][0] == '?') {
		rep(j, 0, N) if (!in(name[j], sentence[i])) {
			rep(k, 0, N) if (k != j && dp[i][k]) {
				dp[i + 1][j] = true;
				pre[i + 1][j] = k;
				break;
			}
		}
	} else {
        int id = -1;
        string s(sentence[i], 0, sentence[i].find(':'));
		rep(j, 0, N) if (s == name[j]) {id = j; break;}
		rep(j, 0, N) if (j != id && dp[i][j]) {
			dp[i + 1][id] = true;
			pre[i + 1][id] = j;
			break;
		}
	}
	rep(i, 0, N)
		if (dp[M][i]) {
			write(M, i);
			return;
		}
	cout << "Impossible" << endl;
}

int main(int argc, char const *argv[])
{
	IOS;
	cin >> t;
	rep(i, 0, t) {
		cin >> N; getline(cin, s);
		rep(i, 0, N)
			cin >> name[i];
		cin >> M; getline(cin, s);
		rep(i, 0, M)
			getline(cin, sentence[i]);
		solve();
	}
	return 0;
}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <bitset>
#define fi first
#define se second
using namespace std;
typedef long long LL;

const int inf = 0x3f3f3f3f;

const int maxn = 1000010*2;
int n,m,T;
char name[1000][1000];
int dp[1000][1000]; //第i条信息可以选择谁？
char str[1000][1000];
int check(char x)
{
	if (x <= 'Z' && x >= 'A') return true;
	if (x <= 'z' && x >= 'a') return true;
	if (x <= '9' && x >= '0') return true;
	return false;
}
int main()
{
	// freopen("in.txt","r",stdin);

	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof dp);
		map <string, int> mp;
		scanf("%d",&n);
		for (int i = 1; i <= n; i++) scanf("%s",name[i]), mp[name[i]] = i;
		scanf("%d",&m);
		getchar();

		for (int i = 1; i <= m; i++)
		{
			gets(str[i]);
			int len = strlen(str[i]);
			if (str[i][0] != '?')
			{
				memset(dp[i],-1,sizeof dp[i]);
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[j] = str[i][j];
					else {
						tmp[j] = '\0';
						break;
					}
				}
				dp[i][mp[tmp]] = 1;
			}
			else
			{
				int cnt = 0;
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[cnt++] = str[i][j];
					else
					{
						tmp[cnt] = '\0';
						dp[i][mp[tmp]] = -1;
						cnt = 0;
					}
				}
			}
		}
		for (int i = 1; i < m; i ++)
		{
			int cnt = 0;
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == -1) cnt++;
			}
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == 1) dp[i+1][j] = -1;
				else if (dp[i][j] == 0 && cnt == n-1) dp[i+1][j] = -1;
			}

		}
		int cnt = 0;
		for (int i = 1; i <= m; i++)
		{
			cnt = 0;
			for (int j = 1; j <= n; j++)
			{
				if (dp[i][j] == -1) cnt ++;
			}
			if (cnt == n) break;
		}
		if (cnt == n) {
			printf("Impossible\n");
		}
		else
		{
			dp[m+1][0] = 0;
			for (int i = m; i >= 1; i--)
			{
				for (int j = 1; j <= n; j++)
				{
					if (dp[i][j] != -1 && dp[m + 1][0] != j) {dp[i][0] = j; break;}
				}
			}

			for (int i = 1; i <= m; i++)
			{
				if (str[i][0] == '?')
				{
					// assert(dp[i][0] > 0 && dp[i][0] <= n)
					printf("%s%s\n",name[dp[i][0]], &str[i][1]);
				}
				else printf("%s\n",str[i] );
			}
		}

	}

}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <cassert>
#include <bitset>
#define fi first
#define se second
using namespace std;
typedef long long LL;

const int inf = 0x3f3f3f3f;

const int maxn = 1000010*2;
int n,m,T;
char name[1000][1000];
int dp[1000][1000]; //第i条信息可以选择谁？
char str[1000][1000];
int check(char x)
{
	if (x <= 'Z' && x >= 'A') return true;
	if (x <= 'z' && x >= 'a') return true;
	if (x <= '9' && x >= '0') return true;
	return false;
}
int main()
{
	// freopen("in.txt","r",stdin);

	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof dp);
		map <string, int> mp;
		scanf("%d",&n);
		for (int i = 1; i <= n; i++) scanf("%s",name[i]), mp[name[i]] = i;
		scanf("%d",&m);
		// cout<<m<<endl;
		char p = getchar();
		// cout<<"---"<<endl;
		for (int i = 1; i <= m; i++)
		{
			gets(str[i]);
			// cout<<str[i]<<endl;
			int len = strlen(str[i]);
			if (str[i][0] != '?')
			{
				memset(dp[i],-1,sizeof dp[i]);
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[j] = str[i][j];
					else {
						tmp[j] = '\0';
						break;
					}
				}
				dp[i][mp[tmp]] = 1;
			}
			else
			{
				int cnt = 0;
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[cnt++] = str[i][j];
					else
					{
						tmp[cnt] = '\0';
						dp[i][mp[tmp]] = -1;
						cnt = 0;
					}
				}
				// cout<<dp[1][1]<<endl;
			}
		}
		// cout<<dp[1][1]<<endl;
		for (int i = 1; i < m; i ++)
		{
			int cnt = 0;
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == -1) cnt++;
			}
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == 1) dp[i+1][j] = -1;
				else if (dp[i][j] == 0 && cnt == n-1) dp[i+1][j] = -1;
			}

		}
		int cnt = 0;
		// cout<<dp[1][1]<<endl;
		for (int i = 1; i <= m; i++)
		{
			cnt = 0;
			for (int j = 1; j <= n; j++)
			{
				// cout<<dp[i][j]<<endl;
				if (dp[i][j] == -1) cnt ++;
			}
			if (cnt == n) break;
		}
		if (cnt == n) {
			printf("Impossible\n");
		}
		else
		{
			dp[m+1][0] = 0;
			for (int i = m; i >= 1; i--)
			{
				dp[i][0] = 0;
				for (int j = 1; j <= n; j++)
				{
					if (dp[i][j] != -1 && dp[m + 1][0] != j) {dp[i][0] = j; break;}
				}
				if (dp[i][0] == 0) assert(0);
			}

			for (int i = 1; i <= m; i++)
			{
				if (str[i][0] == '?')
				{
					assert(dp[i][0] != dp[i+1][0]);
					printf("%s%s\n",name[dp[i][0]], &str[i][1]);
				}
				else
				{
					assert(dp[i][0] != dp[i+1][0]);
					int len = strlen(name[dp[i][0]]);
					printf("%s%s\n",name[dp[i][0]],&str[i][len] );
				}
			}
		}

	}

}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <cassert>
#include <bitset>
#define fi first
#define se second
using namespace std;
typedef long long LL;

const int inf = 0x3f3f3f3f;

const int maxn = 1000010*2;
int n,m,T;
char name[1000][1000];
int dp[1000][1000]; //第i条信息可以选择谁？
char str[1000][1000];
int check(char x)
{
	if (x <= 'Z' && x >= 'A') return true;
	if (x <= 'z' && x >= 'a') return true;
	if (x <= '9' && x >= '0') return true;
	return false;
}
int main()
{
	// freopen("in.txt","r",stdin);

	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof dp);
		map <string, int> mp;
		scanf("%d",&n);
		for (int i = 1; i <= n; i++) scanf("%s",name[i]), mp[name[i]] = i;
		scanf("%d",&m);
		// cout<<m<<endl;
		char p = getchar();
		// cout<<"---"<<endl;
		for (int i = 1; i <= m; i++)
		{
			gets(str[i]);
			// cout<<str[i]<<endl;
			int len = strlen(str[i]);
			if (str[i][0] != '?')
			{
				memset(dp[i],-1,sizeof dp[i]);
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[j] = str[i][j];
					else {
						tmp[j] = '\0';
						break;
					}
				}
				dp[i][mp[tmp]] = 1;
			}
			else
			{
				int cnt = 0;
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[cnt++] = str[i][j];
					else
					{
						tmp[cnt] = '\0';
						dp[i][mp[tmp]] = -1;
						cnt = 0;
					}
				}
				// cout<<dp[1][1]<<endl;
			}
		}
		// cout<<dp[1][1]<<endl;
		for (int i = 1; i < m; i ++)
		{
			int cnt = 0;
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == -1) cnt++;
			}
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == 1) dp[i+1][j] = -1;
				else if (dp[i][j] == 0 && cnt == n-1) dp[i+1][j] = -1;
			}

		}
		int cnt = 0;
		// cout<<dp[1][1]<<endl;
		for (int i = 1; i <= m; i++)
		{
			cnt = 0;
			for (int j = 1; j <= n; j++)
			{
				// cout<<dp[i][j]<<endl;
				if (dp[i][j] == -1) cnt ++;
			}
			if (cnt == n) break;
		}
		if (cnt == n) {
			printf("Impossible\n");
		}
		else
		{
			dp[m+1][0] = 0;
			for (int i = m; i >= 1; i--)
			{
				dp[i][0] = 0;
				for (int j = 1; j <= n; j++)
				{
					if (dp[i][j] != -1 && dp[m + 1][0] != j) {dp[i][0] = j; break;}
				}
				if (dp[i][0] == 0) assert(0);
			}

			for (int i = 1; i <= m; i++)
			{
				if (str[i][0] == '?')
				{
					// assert(dp[i][0] > 0 && dp[i][0] <= n)
					printf("%s%s\n",name[dp[i][0]], &str[i][1]);
				}
				else printf("%s\n",str[i] );
			}
		}

	}

}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <cassert>
#include <bitset>
#define fi first
#define se second
using namespace std;
typedef long long LL;

const int inf = 0x3f3f3f3f;

const int maxn = 1000010*2;
int n,m,T;
char name[1000][1000];
int dp[1000][1000]; //第i条信息可以选择谁？
char str[1000][1000];
int check(char x)
{
	if (x <= 'Z' && x >= 'A') return true;
	if (x <= 'z' && x >= 'a') return true;
	if (x <= '9' && x >= '0') return true;
	return false;
}
int main()
{
	// freopen("in.txt","r",stdin);

	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof dp);
		map <string, int> mp;
		scanf("%d",&n);
		for (int i = 1; i <= n; i++) scanf("%s",name[i]), mp[name[i]] = i;
		scanf("%d",&m);
		getchar();

		for (int i = 1; i <= m; i++)
		{
			gets(str[i]);
			int len = strlen(str[i]);
			if (str[i][0] != '?')
			{
				memset(dp[i],-1,sizeof dp[i]);
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[j] = str[i][j];
					else {
						tmp[j] = '\0';
						break;
					}
				}
				dp[i][mp[tmp]] = 1;
			}
			else
			{
				int cnt = 0;
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[cnt++] = str[i][j];
					else
					{
						tmp[cnt] = '\0';
						dp[i][mp[tmp]] = -1;
						cnt = 0;
					}
				}
			}
		}
		for (int i = 1; i < m; i ++)
		{
			int cnt = 0;
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == -1) cnt++;
			}
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == 1) dp[i+1][j] = -1;
				else if (dp[i][j] == 0 && cnt == n-1) dp[i+1][j] = -1;
			}

		}
		int cnt = 0;
		for (int i = 1; i <= m; i++)
		{
			cnt = 0;
			for (int j = 1; j <= n; j++)
			{
				if (dp[i][j] == -1) cnt ++;
			}
			if (cnt == n) break;
		}
		if (cnt == n) {
			printf("Impossible\n");
		}
		else
		{
			dp[m+1][0] = 0;
			for (int i = m; i >= 1; i--)
			{
				dp[i][0] = 0;
				for (int j = 1; j <= n; j++)
				{
					if (dp[i][j] != -1 && dp[m + 1][0] != j) {dp[i][0] = j; break;}
				}
				if (dp[i][0] == 0) assert(0);
			}

			for (int i = 1; i <= m; i++)
			{
				if (str[i][0] == '?')
				{
					// assert(dp[i][0] > 0 && dp[i][0] <= n)
					printf("%s%s\n",name[dp[i][0]], &str[i][1]);
				}
				else printf("%s\n",str[i] );
			}
		}

	}

}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <utility>
#include <bitset>
#define fi first
#define se second
using namespace std;
typedef long long LL;

const int inf = 0x3f3f3f3f;

const int maxn = 1000010*2;
int n,m,T;
char name[1000][1000];
int dp[1000][1000]; //第i条信息可以选择谁？
char str[1000][1000];
int check(char x)
{
	if (x <= 'Z' && x >= 'A') return true;
	if (x <= 'z' && x >= 'a') return true;
	if (x <= '9' && x >= '0') return true;
	return false;
}
int main()
{
	// freopen("in.txt","r",stdin);

	scanf("%d",&T);
	while(T--)
	{
		memset(dp,0,sizeof dp);
		map <string, int> mp;
		scanf("%d",&n);
		for (int i = 1; i <= n; i++) scanf("%s",name[i]), mp[name[i]] = i;
		scanf("%d",&m);
		getchar();

		for (int i = 1; i <= m; i++)
		{
			gets(str[i]);
			int len = strlen(str[i]);
			if (str[i][0] != '?')
			{
				memset(dp[i],-1,sizeof dp[i]);
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[j] = str[i][j];
					else {
						tmp[j] = '\0';
						break;
					}
				}
				dp[i][mp[tmp]] = 1;
			}
			else
			{
				int cnt = 0;
				char tmp[1000];
				for (int j = 0; j < len + 1; j++)
				{
					if (check(str[i][j])) tmp[cnt++] = str[i][j];
					else
					{
						tmp[cnt] = '\0';
						dp[i][mp[tmp]] = -1;
						cnt = 0;
					}
				}
			}
		}
		for (int i = 1; i < m; i ++)
		{
			int cnt = 0;
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == -1) cnt++;
			}
			for (int j = 1; j <= n; j ++)
			{
				if (dp[i][j] == 1) dp[i+1][j] = -1;
				else if (dp[i][j] == 0 && cnt == n-1) dp[i+1][j] = -1;
			}

		}
		int cnt = 0;
		for (int i = 1; i <= m; i++)
		{
			cnt = 0;
			for (int j = 1; j <= n; j++)
			{
				if (dp[i][j] == -1) cnt ++;
			}
			if (cnt == n) break;
		}
		if (cnt == n) {
			printf("Impossible\n");
		}
		else
		{
			dp[m+1][0] = 0;
			for (int i = m; i >= 1; i--)
			{
				for (int j = 1; j <= n; j++)
				{
					if (dp[i][j] != -1 && dp[m + 1][0] != j) {dp[i][0] = j; break;}
				}
			}

			for (int i = 1; i <= n; i++)
			{
				if (str[i][0] == '?') printf("%s%s\n",name[dp[i][0]], &str[i][1]);
				else printf("%s\n",str[i] );
			}
		}

	}

}