题意:
给你一个矩阵 有两种操作:
1 这一行每个都加一
2 这一列每个都加一
问你怎么用最少的步数从都是0的矩阵变到给的矩阵
思路:
输出的时候记录一下sum 用来验证是否成立
因为要最少的 所以先可行或列小的来变
每一次找这一行或一列最小的 然后加上到相应的队列中
然后sum减去对应的值
如果最后sum!=0 那么不存在这种变化
等于0的话就把队列中的打印出来
1 #include<bits/stdc++.h> 2 #define cl(a,b) memset(a,b,sizeof(a)) 3 #define debug(a) cerr<<#a<<"=="<<a<<endl 4 using namespace std; 5 typedef long long ll; 6 typedef pair<int,int> pii; 7 8 const int maxn=100+10; 9 10 int n,m; 11 int num[maxn][maxn]; 12 int cnt=0,sum=0; 13 vector<int>ansr; 14 vector<int>ansc; 15 16 void col() //列 17 { 18 for(int j=0;j<m;j++) 19 { 20 int mn=INT_MAX; 21 for(int i=0;i<n;i++) 22 { 23 mn=min(mn,num[i][j]); 24 } 25 for(int i=0;i<n;i++) 26 { 27 num[i][j]-=mn; 28 } 29 sum-=mn*n; 30 for(int i=0;i<mn;i++) 31 { 32 ansc.push_back(j); 33 } 34 } 35 } 36 37 void row() //行 38 { 39 for(int i=0;i<n;i++) 40 { 41 int mn=INT_MAX; 42 for(int j=0;j<m;j++) 43 { 44 mn=min(mn,num[i][j]); 45 } 46 for(int j=0;j<m;j++) 47 { 48 num[i][j]-=mn; 49 } 50 sum-=mn*m; 51 for(int j=0;j<mn;j++) 52 { 53 ansr.push_back(i); 54 } 55 } 56 } 57 58 int main() 59 { 60 scanf("%d%d",&n,&m); 61 for(int i=0;i<n;i++) 62 { 63 for(int j=0;j<m;j++) 64 { 65 scanf("%d",&num[i][j]); 66 sum+=num[i][j]; 67 } 68 } 69 if(n>m) 70 { 71 col(); 72 row(); 73 } 74 else 75 { 76 row(); 77 col(); 78 } 79 if(sum!=0) 80 { 81 puts("-1"); 82 return 0; 83 } 84 printf("%d ",ansc.size()+ansr.size()); 85 for(auto i:ansc) 86 { 87 printf("col %d ",i+1); 88 } 89 for(auto i:ansr) 90 { 91 printf("row %d ",i+1); 92 } 93 return 0; 94 }/* 95 96 3 5 97 2 2 2 3 2 98 0 0 0 1 0 99 1 1 1 2 1 100 101 */