杭电oj HDOJ 1031 Design T-Shirt
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1031
Problem Description
Soon after he decided to design a T-shirt for our Algorithm Board on Free-City BBS, XKA found that he was trapped by all kinds of suggestions from everyone on the board. It is indeed a mission-impossible to have everybody perfectly satisfied. So he took a poll to collect people’s opinions. Here are what he obtained: N people voted for M design elements (such as the ACM-ICPC logo, big names in computer science, well-known graphs, etc.). Everyone assigned each element a number of satisfaction. However, XKA can only put K (<=M) elements into his design. He needs you to pick for him the K elements such that the total number of satisfaction is maximized.
Input
The input consists of multiple test cases. For each case, the first line contains three positive integers N, M and K where N is the number of people, M is the number of design elements, and K is the number of elements XKA will put into his design. Then N lines follow, each contains M numbers. The j-th number in the i-th line represents the i-th person’s satisfaction on the j-th element.
Output
For each test case, print in one line the indices of the K elements you would suggest XKA to take into consideration so that the total number of satisfaction is maximized. If there are more than one solutions, you must output the one with minimal indices. The indices start from 1 and must be printed in non-increasing order. There must be exactly one space between two adjacent indices, and no extra space at the end of the line.
解题思路
先把某个人对同一个设计元素的满意度累加起来用数组存储,再找出最大的K的满意度元素,按“递减”的顺序输出这K个元素在数组中的下标。
本人的C++解决方案
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main()
{
int N, M, K, i, j, pos, res[100], max;
double sat[101], temp;
bool mark[101];
while (cin >> N >> M >> K) {
memset(sat, 0, sizeof(sat));
memset(mark, 1, sizeof(mark));
pos = 0;
for (i = 0; i < N; i++) {
for (j = 1; j <= M; j++) {
cin >> temp;
sat[j] += temp;
}
}
// 找出最大的K的满意度元素
while (pos < K) {
max = 0;
for (i = 1; i <= M; i++) {
if (sat[i] > sat[max] && mark[i]) {
max = i;
}
}
res[pos++] = max;
mark[max] = false;
}
// 对K个元素进行排序
sort(res, res + K);
for (i = K - 1; i >= 0; i--) {
if (i != K - 1) {
printf(" ");
}
printf("%d", res[i]);
}
printf("\n");
}
}
代码通过HDOJ平台运行检查,如发现错误,欢迎指出和纠正,谢谢!