2019 JUST Programming Contest J. Grid Beauty
You are given a grid gg consisting of nn rows each of which is divided into mm columns.
You can swap any two integers in the same row infinitely, but you cannot swap two integers from two different rows.
Your task is to maximize the beauty of the grid by rearranging integers in each row. The beauty of the grid is the number of pairs (i,j ) (1<i≤n,1≤j≤m ) such that gi,jgi,j is equal to gi−1,j (i.e. gi,j≡gi−1 ).
The first line contains an integer T (1≤T≤5 ) specifying the number of test cases.
The first line of each test case contains two integers nn and mm (1≤n,m≤103 ), giving the number of rows and columns in the grid, respectively.
Then nn lines follow, each line contains mm integers, giving the grid. All values in the grid are between 1 and 108 (inclusive).
For each test case, print a single line containing the beauty of the grid.
2 2 3 1 2 3 4 1 2 3 3 5 7 9 3 2 9 5 3 2
2 3
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
解题思路:这道题就是给说如果a[i][j] = a[i-1][j]则是美丽的,问你说最多有几个;
这道题我是卡着时间过的,用map超时了,用unorder_map变快了,可能有其他人有很多更好的做法,下面是我的做法;
1 #include<iostream> 2 #include<stdio.h> 3 #include<unordered_map> //unordered_map的头文件; 4 #include<algorithm> 5 using namespace std; 6 7 int n ; 8 int row , col; 9 int a[1005][1005]; 10 unordered_map<int,int>flag; //用来记录当前行出现了数字出现多少个; 11 unordered_map<int,int>flag1; //用来记录下一行的数字出现多少个; 12 int ans = 0 ; 13 14 int main() 15 { 16 scanf("%d",&n); 17 while(n--) 18 { 19 ans = 0; 20 scanf("%d%d",&row,&col); 21 for(int i = 0 ;i < row ;i++) 22 { 23 for(int j = 0 ; j < col ;j++) 24 { 25 scanf("%d",&a[i][j]); 26 } 27 28 } 29 for(int i = 0 ; i < row-1 ;i++ ) 30 { 31 for(int j = 0 ; j < col ;j++) 32 { 33 34 flag[a[i][j]]++; //统计每个数字出现的个数; 35 flag1[a[i+1][j]]++; //统计下一行每个数字出现的个数; 36 } 37 for(int j = 0 ; j < col ; j++) 38 { 39 40 if(flag1[a[i+1][j]]>0) //如果这一行的数字在下一行出现过; 41 { 42 ans += min(flag[a[i+1][j]],flag1[a[i+1][j]]); 43 //不断取这一行和下一行的较小者; 44 flag1[a[i+1][j]] = 0; 45 //并将统计过的数字个数重新置为0; 46 } 47 } 48 for(int j = 0 ; j < col ;j++) 49 { 50 flag[a[i][j]] = 0; 51 flag1[a[i+1][j]] = 0; 52 //初始化,方便后面的行的比较,比如比较了第一和第二行,现在比较第二和第三行,所以每个数字出现的个数要重新置为0; 53 } 54 } 55 printf("%d\n",ans); 56 } 57 return 0 ; 58 }