codeforce 985C Liebig's Barrels(貪心+思維)
You have m?=?n·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.
Let volume vj of barrel j be equal to the length of the minimal stave in it.
You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |vx?-?vy|?≤?l
Print maximal total sum of volumes of equal enough barrels or 0 if it‘s impossible to satisfy the condition above.
InputThe first line contains three space-separated integers n, k and l (1?≤?n,?k?≤?105, 1?≤?n·k?≤?105, 0?≤?l?≤?109).
The second line contains m?=?n·k space-separated integers a
Print single integer — maximal total sum of the volumes of barrels or 0 if it‘s impossible to construct exactly n barrels satisfying the condition |vx?-?vy|?≤?l for any 1?≤?x?≤?n and 1?≤?y?≤?n.
Examples input Copy4 2 1output Copy
2 2 1 2 3 2 2 3
7input Copy
2 1 0output Copy
10 10
20input Copy
1 2 1output Copy
5 2
2input Copy
3 2 1output Copy
1 2 3 4 5 6
0Note
In the first example you can form the following barrels: [1,?2], [2,?2], [2,?3], [2,?3].
In the second example you can form the following barrels: [10], [10].
In the third example you can form the following barrels: [2,?5].
In the fourth example difference between volumes of barrels in any partition is at least 2 so it is impossible to make barrels equal enough.
題意:輸入 n k l 你要做n個桶,每個桶需要k個木板,用木板拼好的桶相互之間體積的差距<=l,桶的體積大小就是最短的那根木板的長度大小。
第二行 共n*k個數,分別表示n*k個木板的長度。
分析:
先對邊排個序
不存在的情況,就是a[n]-a[1]>l,那就是不存在,因為要是差距盡可能小,前n小的都分別作為n個桶的一塊木板,那麽這之中最大的差距就是a[n]-a[1],要是a[n]-a[1]都滿足條件(<=l)了,那就滿足條件了。
其次,要使體積和最大輸出體積和,我毛想想覺得s=a[1]+……a[n],結果WA了,引起了我的深思。
因為:
eg:4 3 17
1 2 3 5 9 13 18 21 22 23 25 26
它可以這樣組3組:
18 25 26
13 22 23
1 2 3
5 9 21
這樣體積為1+5+13+18=37,不是簡單地1 +2 +3 +5=11
所以我的思路:先要找到最大的滿足條件的數,可以用二分找更快,在這組樣例中,是18,它-a[1]<=l,
那麽從最後開始去k-1個和18拼,s+=18,再下一個數13(25 26),再從最後找k-1個數(22 23),
再下一個數9,發現再k-1個數不夠了,那就從頭開始找了,(1 2 3)一組,在去(5 9 13)時,發現13
已經被取走,那就s+=5就可以了。
#include <iostream> #include<cstring> #include<string> #include<cstdio> #include<algorithm> #include<cmath> #include<deque> #include<vector> #define ll long long #define inf 0x3f3f3f3f #define mod 1000000007; using namespace std; ll a[100005]; bool cmp(ll a,ll b) { return a<b; } int main() { ll n,k,l; scanf("%I64d%I64d%I64d",&n,&k,&l); for(ll i=1;i<=n*k;i++) { scanf("%I64d",&a[i]); } sort(a+1,a+1+n*k,cmp); if(a[n]-a[1]>l) { printf("0"); } else { ll s=0; ll p=-1; for(ll i=n*k;i>=1;i--) { if(a[i]-a[1]<=l) { p=i;//找到標準數,最大的滿足條件的數 break; } } s=0; int num=0;//記錄從標準數向前取了多少 int j=p; for(ll i=n*k;i-(k-1)>p;i=i-(k-1))//先從後往前取 { s+=a[j--]; num++; } for(ll i=1;i<p-num+1;i=i+k)//在從前往後取 { s+=a[i]; } printf("%I64d",s); } return 0; }
codeforce 985C Liebig's Barrels(貪心+思維)