[Google Code Jam (Round 1A 2008) ] A. Minimum Scalar Product

Problem A. Minimum Scalar Product

 
This contest is open for practice. You can try every problem as many times as you like, though we won't keep track of which problems you solve. Read the Quick-Start Guide to get started.

Problem

You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.

Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

Input

The first line of the input file contains integer number T - the number of test cases. For each test case, the first line contains integer number n. The next two lines contain n integers each, giving the coordinates of v 1 and v 2 respectively.

 

Output

For each test case, output a line

Case #X: Y
where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.

 

Limits

 

Small dataset

T = 1000
1 ≤ n ≤ 8
-1000 ≤ xi, yi ≤ 1000

Large dataset

T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000

Sample


Input 
 

Output 
 
2
3
1 3 -5
-2 4 1
5
1 2 3 4 5
1 0 1 0 1

Case #1: -25
Case #2: 6
题解:排序不等式的应用。
 
排序不等式公式
0<a1<a2<a3......<an
0<b1<b2<b3......<bn
an×bn+an-1×bn-1+......+a1×b1>=乱序和>=a1×bn+a2×bn-1+......+an×b1
(注:n,n-1,n-2等,均为角标)
 
顺序不等式基本形式:

排序不等式的证明

分析法
要证
只需证
根据基本不等式
只需证
∴原结论正确
 
代码:
 1 #include<stdio.h>

 2 #include<string.h>

 3 

 4 int i,j,n,m;

 5 

 6 long long    a[1000],b[1000];

 7 

 8 long long sum;

 9 

10 int 

11 pre()

12 {

13     memset(a,0,sizeof(a));

14     memset(b,0,sizeof(b));

15     sum=0;

16     return 0;

17 }

18 

19 int 

20 init()

21 {

22     scanf("%d",&n);

23     for(i=1;i<=n;i++)

24     scanf("%lld",&a[i]);

25     for(i=1;i<=n;i++)

26     scanf("%lld",&b[i]);

27     

28     return 0;

29 }

30 

31 void

32 qsort(long long a[],int head,int tail)

33 {

34     int i,j;

35     long long x;

36     i=head;j=tail;

37     x=a[head];

38     

39     while(i<j)

40     {

41         while((i<j)&(a[j]>=x)) j--;

42         a[i]=a[j];

43         while((i<j)&(a[i]<=x)) i++;

44         a[j]=a[i];

45     }

46     a[i]=x;

47     

48     if(head<(i-1)) qsort(a,head,i-1);

49     if((i+1)<tail) qsort(a,i+1,tail);

50 }

51 

52 

53 int 

54 main()

55 {

56     int casi,cas;

57     freopen("1.in","r",stdin);

58     freopen("1.out","w",stdout);

59     scanf("%d",&cas);

60 for(casi=1;casi<=cas;casi++)

61 {

62     pre();

63     init();

64     qsort(a,1,n);

65     qsort(b,1,n);

66     

67     for(i=1;i<=n;i++)

68     sum+=a[i]*b[n-i+1];

69     

70     printf("Case #%d: %lld\n",casi,sum);

71 }

72     return 0;

73 }

74     

 

 
 
 

你可能感兴趣的:(Google)