您的位置:首页 > 编程语言

编程之美2014资格赛题目3:格格取数

2014-04-13 21:30 531 查看


编程之美2014资格赛题目3:格格取数

时间限制:2000ms
单点时限:1000ms
内存限制:256MB


描述

给你一个m x n (1 <= m, n <= 100)的矩阵A (0<=aij<=10000),要求在矩阵中选择一些数,要求每一行,每一列都至少选到了一个数,使得选出的数的和尽量的小。

 


输入

多组测试数据。首先是数据组数T

对于每组测试数据,第1行是两个正整数m, n,分别表示矩阵的行数和列数。

接下来的m行,每行n个整数,之间用一个空格分隔,表示矩阵A的元素。

 


输出

每组数据输出一行,表示选出的数的和的最小值。

 


数据范围

小数据:1 <= m, n <= 5

大数据:1 <= m, n <= 100

 

 

样例输入
2 3 3 1 2 3 3 1 2 2 3 1 5 5 1 2 3 4 5 5 1 2 3 4 4 5 1 2 3 3 4 5 1 2 2 3 4 5 1


样例输出
Case 1: 3 Case 2: 5

代码如下:

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int last;//剩下未覆盖的边或行数
int boolx[100];//经过边或行的数量
int booly[100];
int m,n;//行数,列数
unsigned int mini;
typedef struct point{
unsigned int v;//值
unsigned int x;//坐标
unsigned int y;
};

bool more(const point &a,const point &b){
return a.v>b.v;
}
bool lesss(const point &a,const point &b){
return a.v<b.v;
}
vector<point> all;
vector<point> np;
void delp(int x,int y,int v){//
if(boolx[x]>1&&booly[y]>1){
boolx[x]--;
booly[y]--;
}else mini += v;
}
void addp(int x,int y){
if(boolx[x] == 0)last--;
if(booly[y] == 0)last--;
boolx[x]++;
booly[y]++;
}
int main(){
int i,j,T,t = 1;
unsigned int s;
cin>>T;
point p;
while(T--){
cin>>m>>n;
for( i = 0 ;i<m;i++){
for( j = 0;j<n;j++){
cin>>s;
p.x = i;
p.y = j;
p.v = s;
all.push_back(p);
boolx[i] = 0;
booly[j] = 0;
}
}
sort(all.begin(),all.end(),lesss);
last = n + m;
i = 0;
while(last > 0){
addp(all[i].x,all[i].y);
np.push_back(all[i++]);
}
mini = 0;
sort(np.begin(),np.end(),more);
for( i =0; i<np.size();i++)
delp(np[i].x,np[i].y,np[i].v);
all.clear();
np.clear();
printf("Case %d: ",t++);
cout<<mini<<endl;
}

return 0;
} #include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int last;//剩下未覆盖的边或行数
int boolx[100];//经过边或行的数量
int booly[100];
int m,n;//行数,列数
unsigned int mini;
typedef struct point{
unsigned int v;//值
unsigned int x;//坐标
unsigned int y;
};

bool more(const point &a,const point &b){
return a.v>b.v;
}
bool lesss(const point &a,const point &b){
return a.v<b.v;
}
vector<point> all;
vector<point> np;
void delp(int x,int y,int v){//
if(boolx[x]>1&&booly[y]>1){
boolx[x]--;
booly[y]--;
}else mini += v;
}
void addp(int x,int y){
if(boolx[x] == 0)last--;
if(booly[y] == 0)last--;
boolx[x]++;
booly[y]++;
}
int main(){
int i,j,T,t = 1;
unsigned int s;
cin>>T;
point p;
while(T--){
cin>>m>>n;
for( i = 0 ;i<m;i++){
for( j = 0;j<n;j++){
cin>>s;
p.x = i;
p.y = j;
p.v = s;
all.push_back(p);
boolx[i] = 0;
booly[j] = 0;
}
}
sort(all.begin(),all.end(),lesss);
last = n + m;
i = 0;
while(last > 0){
addp(all[i].x,all[i].y);
np.push_back(all[i++]);
}
mini = 0;
sort(np.begin(),np.end(),more);
for( i =0; i<np.size();i++)
delp(np[i].x,np[i].y,np[i].v);
all.clear();
np.clear();
printf("Case %d: ",t++);
cout<<mini<<endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: