2 3 4 2 4 5 8 6 2 1 9 4 6 8 5 2 3 1 2 3 10 12 10
1 7
感觉可以看成是贪心的一种,参考了别人的代码,顺便解释下
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<cstdio> 5 using namespace std; 6 bool vis[210]; 7 struct Node 8 { 9 int x ,y; 10 }node[2200]; 11 bool cmp(struct Node x ,struct Node y) 12 { 13 return x.x<y.x; 14 } 15 int solve(int n,int m) 16 { 17 int i,j ,temp,temp1, ans; 18 ans=999999999; 19 for(i=0;i<n;i++) 20 { 21 temp=1; 22 memset(vis,false,sizeof(vis)); 23 vis[node[i].y]=true; //每个数上都有标记 24 for(j=i;j<n;j++) 25 { 26 if(!vis[node[j].y])//如果该行还没有选 27 { 28 temp++; //选出一行 29 vis[node[j].y]=true; 30 if(temp==m) //如果正好够m个了,则拿最大的减去最小的,得到最小的 31 { 32 if((node[j].x-node[i].x)<ans) 33 { 34 ans=node[j].x-node[i].x; 35 } 36 break; 37 } 38 } 39 } 40 } 41 return ans; 42 } 43 int main() 44 { 45 int T ,n, m; 46 cin>>T; 47 while(T--) 48 { 49 cin>>n>>m; 50 int temp=0; 51 for(int i=1; i<=n; i++) 52 { 53 for(int j=0;j<m;j++) 54 { 55 cin>>node[temp].x; //对所有的进行排序 56 node[temp++].y=i; //并标记所在的行 57 } 58 } 59 sort(node,node+temp,cmp); //对所有的进行排序 60 cout<<solve(temp,n)<<endl; 61 } 62 return 0; 63 }
原文:http://www.cnblogs.com/lovychen/p/3585244.html