单点时限: 2.0 sec
内存限制: 256 MB
有一个 n (1<n≤100) 行组成的两维整数数组 (每行有 m 个元素,1<m≤M),对数组的行按以下顺序排序:按每行所有元素值的和从小到大排序。行的和相同时比较行内第 1 个元素的值,小的排在前面,若第 1 个元素的值也相等,则比较第 2 个元素,以此类推。
只需按要求写出函数定义,并使用给定的测试程序测试你所定义函数的正确性。
不要改动测试程序。测试正确后,将测试程序和函数定义一起提交。
#define M 100
//********** Specification of SortLines**********
void SortLines(int (p)[M], int n, int m);
/ PreCondition:
p points to a two-dimensional array with n lines and
m integers in each line
PostCondition:
array is sorted satisfying to the specification
*/
/**************************************************************/
/ /
/ DON’T MODIFY main function ANYWAY! /
/ /
/****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 100
#define N 100
// Specification of SortLines **********
void SortLines(int (p)[M], int n, int m)
/ PreCondition:
p points to a two-dimensional array with n lines and
m integers in each line
PostCondition:
array is sorted satisfying to the specification
/
{ //TODO: your function definition
}
/*****************/
int main()
{
int a[N][M];
int n,m,i,j;
int t,cas;
scanf("%d",&cas);
for(t=0; t<cas; t++)
{
memset(a,0,sizeof(a));
scanf("%d%d",&n,&m);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
scanf("%d",&a[i][j]);
/ function SortLines is called here *****/
SortLines(a,n,m);
//
printf(“case #%d:\n”,t);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
printf("%d%c",a[i][j],j<m-1?’ ‘:’\n’);
}
return 0;
}
/*
思路:模拟一维数组排序
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 100
#define N 100
int f(int *a,int n) {
int sum=0;
for(int i = 0; i < n; i++)
sum+=a[i];
return sum;
}
void swap(int *a,int *b,int m) {
for(int i = 0; i < m; i++) {
int t=a[i];
a[i]=b[i];
b[i]=t;
}
}
//********** Specification of SortLines **********
void SortLines(int (*p)[M], int n, int m)
/* PreCondition:
p points to a two-dimensional array with n lines and
m integers in each line
PostCondition:
array is sorted satisfying to the specification
*/
{
//TODO: your function definition
for(int i = 0; i < n; i++) {//5342
for(int j = i+1; j < n; j++) {
int sum1=f(p[i],m);
int sum2=f(p[j],m);
if(sum1>sum2) {
sum1=sum2;
swap(p[i],p[j],m);
} else if(sum1==sum2) {
int z=0;
while(p[i][z]==p[j][z]&&z<m)
z++;
if(z<m&&p[i][z]>p[j][z])
swap(p[i],p[j],m);
}
}
}
}
/***************************************************************/
int main() {
int a[N][M];
int n,m,i,j;
int t,cas;
scanf("%d",&cas);
for(t=0; t<cas; t++) {
memset(a,0,sizeof(a));
scanf("%d%d",&n,&m);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
scanf("%d",&a[i][j]);
/***** function SortLines is called here *****/
SortLines(a,n,m);
/****************************************/
printf("case #%d:\n",t);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
printf("%d%c",a[i][j],j<m-1?' ':'\n');
}
return 0;
}