Uva--11100(贪心,数学)
2014-07-27 13:55:32
Problem A: The Trip, 2007
A number of students are members of a club that travels annually to exotic locations. Their destinations in the past have included Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, Atlanta, Eindhoven, Orlando, Vancouver, Honolulu, Beverly Hills, Prague, Shanghai, and San Antonio. This spring they are hoping to make a similar trip but aren't quite sure where or when.
An issue with the trip is that their very generous sponsors always give them various knapsacks and other carrying bags that they must pack for their trip home. As the airline allows only so many pieces of luggage, they decide to pool their gifts and to pack one bag within another so as to minimize the total number of pieces they must carry.
The bags are all exactly the same shape and differ only in their linear dimension which is a positive integer not exceeding 1000000. A bag with smaller dimension will fit in one with larger dimension. You are to compute which bags to pack within which others so as to minimize the overall number of pieces of luggage (i.e. the number of outermost bags). While maintaining the minimal number of pieces you are also to minimize the total number of bags in any one piece that must be carried.
Standard input contains several test cases. Each test case consists of an integer 1 ≤ n ≤ 10000 giving the number of bags followed by nintegers on one or more lines, each giving the dimension of a piece. A line containing 0 follows the last test case. For each test case your output should consist of k, the minimum number of pieces, followed by k lines, each giving the dimensions of the bags comprising one piece, separated by spaces. Each dimension in the input should appear exactly once in the output, and the bags in each piece must fit nested one within another. If there is more than one solution, any will do. Output an empty line between cases.
Sample Input
6 1 1 2 2 2 3 0
Output for Sample Input
3 1 2 1 2 3 2
思路:这题有技巧,首先分组数是元素重复出现次数的最大值 m,那么每一组都有这个元素(样例中为2),只要开一个循环for i = 0 to m - 1 (i < n),每次i += m,就可以扫出所有的数,
并且保证每组的数不重复(具体见程序)
1 /************************************************************************* 2 > File Name: j.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Fri 25 Jul 2014 04:36:31 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 16 int n,v[10005],num[1000005],k; 17 18 int main(){ 19 while(scanf("%d",&n) == 1 && n){ 20 memset(num,0,sizeof(num)); 21 k = 0; 22 for(int i = 0; i < n; ++i){ 23 scanf("%d",&v[i]); 24 ++num[v[i]]; 25 k = num[v[i]] > k ? num[v[i]] : k; 26 } 27 sort(v,v + n); 28 printf("%d\n",k); 29 for(int i = 0; i < k; ++i){ 30 printf("%d",v[i]); 31 for(int j = i + k; j < n; j += k) 32 printf(" %d",v[j]); 33 printf("\n"); 34 } 35 } 36 return 0; 37 }