题目很好理解,将列求和,取前k大的
我的代码思路:对列求和,后取出前k大的id加入结果数组,对比后面和第k大相同的评分id也加入到结果数组,最后对结果数组排序
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int Max = ;
struct Node{
double score;
int id;
bool operator < (const Node o) const{
return score>o.score;
}
}node[Max];
int ans[Max];
int main()
{
int n,m,k;
while(~scanf("%d%d%d",&n,&m,&k))
{
double tm;
for(int i = ; i < m; i++){
node[i].id = i;
node[i].score = ;
}
for(int i = ; i < n; i++){
for(int j = ; j < m; j++){
scanf("%lf",&tm);
node[j].score+=tm;
}
}
sort(node,node+m);
int cnt = ;
for(int i = ; i < k; i++){
ans[cnt++] = node[i].id+;
}
int top = k;
while(node[top].score==node[top-].score){
ans[cnt++] = node[top].id;
top++;
}
sort(ans,ans+cnt);
for(int i = k-; i > ; i--){
printf("%d ",ans[i]);
}
printf("%d\n",ans[]);
}
return ;
}
(有一种wa的痛叫忘记数组初始化)
下面是看了大神的代码,原来自己想复杂了,直接对结构体进行两次排序即可
get一种新方法,记录代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int Max = ;
struct Node{
double score;
int id;
}node[Max];
bool cmpByScore(Node a, Node b){
return a.score>b.score;
}
bool cmpById(Node a, Node b){
return a.id>b.id;
}
int main()
{
int n,m,k;
while(~scanf("%d%d%d",&n,&m,&k))
{
double tm;
for(int i = ; i < m; i++){
node[i].id = i+;
node[i].score = ;
}
for(int i = ; i < n; i++){
for(int j = ; j < m; j++){
scanf("%lf",&tm);
node[j].score+=tm;
}
}
sort(node,node+m,cmpByScore);
sort(node,node+k,cmpById);
for(int i = ; i < k-; i++){
printf("%d ",node[i].id);
}
printf("%d\n",node[k-].id);
}
return ;
}