B. A New Technique(思维)Codeforces Round #679 (Div. 2, based on Technocup 2021 Elimination Round 1)

原题链接: https://codeforces.com/contest/1435/problem/B

在这里插入图片描述
测试样例

input
2
2 3
6 5 4
1 2 3
1 6
2 5
3 4
3 1
2
3
1
3 1 2
output
1 2 3
6 5 4
3
1
2

Note

Consider the first test case. The matrix is 2 × 3 2×3 2×3. You are given the rows and columns in arbitrary order.
One of the rows is [ 6 , 5 , 4 ] [6,5,4] [6,5,4]. One of the rows is [ 1 , 2 , 3 ] [1,2,3] [1,2,3].
One of the columns is [ 1 , 6 ] [1,6] [1,6]. One of the columns is [ 2 , 5 ] [2,5] [2,5]. One of the columns is [ 3 , 4 ] [3,4] [3,4].
You are to reconstruct the matrix. The answer is given in the output.

题意: 现在有一个 n × m n\times m n×m的矩阵,但不记得它的排列,只知道相关的行和列的排列,请你恢复这个矩阵。

解题思路: 首先我们要知道,矩阵如果确定了行,那么它的列也就可以确定了,如果我们不知道行的先后顺序,那么我们自然可以根据列来比对查找。(因为元素不会存在相同的情况。)故我们的方案就是通过寻找行的先后顺序来实现矩阵的还原。具体看代码。

AC代码

/*
*邮箱:[email protected]
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>	//POJ不支持

#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair

using namespace std;

const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//

int t,n,m;
int a[503][503];
int b[503][503];
int main(){
    
    
	//freopen("in.txt", "r", stdin);//提交的时候要注释掉
	IOS;
	while(cin>>t){
    
    
		while(t--){
    
    
			cin>>n>>m;
			rep(i,1,n){
    
    
				rep(j,1,m){
    
    
					cin>>a[i][j];
				}
			}
			rep(i,1,m){
    
    
				rep(j,1,n){
    
    
					cin>>b[i][j];
				}
			}
			vector<int> result;
			bool flag;
			rep(i,1,n){
    
    
				flag=false;
				rep(j,1,n){
    
    
					rep(k,1,m){
    
    
						if(b[1][i]==a[j][k]){
    
    
							result.push_back(j);
							flag=true;
							break;
						}
					}
					if(flag)break;
				}
			}
			rep(i,0,n-1){
    
    
				rep(j,1,m){
    
    
					cout<<a[result[i]][j]<<" ";
				}
				cout<<endl;
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hzf0701/article/details/109310395