Cut Pieces
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others) Total Submission(s): 728 Accepted Submission(s): 303
Problem Description
Suppose we have a sequence of n blocks. Then we paint the blocks. Each block should be painted a single color and block i can have color 1 to color ai. So there are a total of prod(ai) different ways to color the blocks. Consider one way to color the blocks. We call a consecutive sequence of blocks with the same color a "piece". For example, sequence "Yellow Yellow Red" has two pieces and sequence "Yellow Red Blue Blue Yellow" has four pieces. What is S, the total number of pieces of all possible ways to color the blocks?
This is not your task. Your task is to permute the blocks (together with its corresponding ai) so that S is maximized.
This is not your task. Your task is to permute the blocks (together with its corresponding ai) so that S is maximized.
Input
First line, number of test cases, T. Following are 2*T lines. For every two lines, the first line is n, length of sequence; the second line contains n numbers, a1, ..., an.
Sum of all n <= 106. All numbers in the input are positive integers no larger than 109.
Sum of all n <= 106. All numbers in the input are positive integers no larger than 109.
Output
Output contains T lines. Each line contains one number, the answer to the corresponding test case. Since the answers can be very large, you should output them modulo 109+7.
Sample Input
1
3
1 2 3
3
1 2 3
Sample Output
14
Hint
Both sequence 1 3 2 and sequence 2 3 1 result in an S of 14.
Source
Recommend
zhuyuanchen520
对于一个序列:a,b,c,d,e,f....
设sum=a*b*c*d*....;
对于a,b,当a与b不同的时候可以增加(ab-min(a,b))*(sum/ab)=(s-s/max(a,b));
max(a,b)越大,增加的也就越大!所以当然让大的数多取,
比如:n=7的时候
对于序列1 2 3 4 5 6 7
我可以排列成
1 5 2 6 3 7 4;
这样我就使得最大的三个数(5,6,7)都取了两次,从而答案是最优的!!!
n=6的时候
对于序列1 2 3 4 5 6
可以排列成
1 5 2 6 3
还有个4就只能放边上了!!!
即5,6都取了两次,而4只能取1次啦!!!
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
#define MAX 1000010
#define mod 1000000007
using namespace std;
typedef long long ll; int ext_gcd(int a,int b,int &x,int &y)
{
if(b==){x=;y=;return a;}
int d=ext_gcd(b,a%b,x,y),t;
t=x;x=y;y=t-a/b*y;
return d;
}
int inv(int a,int mo)
{
int x,y,dx,g;
g=ext_gcd(a,mo,x,y);
dx=mo/g;
return (x%dx+dx)%dx;
} int a[];
int main()
{
int head,tail,T,i,n,jnm;
ll ji,ans;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
ji=;
for(i=;i<=n;i++)
{
scanf("%d",&a[i]);
ji*=a[i];
ji%=mod;
}
sort(a+,a+n+);
ans=ji;
head=n-n/+;
tail=n;
if(n&)//区分奇偶的区别!!!!
ans=((ans+*(ji-ji*inv(a[head-],mod)%mod))%mod+mod)%mod;
else
ans=((ans+*(ji-ji*inv(a[head-],mod)%mod))%mod+mod)%mod;
for(i=head;i<=tail;i++)
ans=((ans+*(ji-ji*inv(a[i],mod)%mod))%mod+mod)%mod;
if(n==)ans=a[];
printf("%lld\n",ans);
}
return ;
}