欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

2019ICPC(沈阳) - Flowers(二分)

发布时间:2024/4/11 编程问答 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 2019ICPC(沈阳) - Flowers(二分) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目链接:点击查看

题目大意:给出 nnn 种颜色不同的鲜花,每种花有 aia_iai 个,现在规定 mmm 个不同的鲜花可以扎成一束,问最多可以扎多少束鲜花

题目分析:考虑问题的简化版:有三种颜色不同的袜子,分别有 a,b,ca,b,ca,b,c 个,任意两个颜色不同的袜子可以互相匹配,问最多可以匹配多少个,解法也很简单,记 sum=a+b+c,mmax=max(a,b,c)sum=a+b+c,mmax=max(a,b,c)sum=a+b+c,mmax=max(a,b,c),则:

  • mmax≤sum−mmaxmmax\le sum-mmaxmmaxsummmax:答案为 ⌊sum2⌋\lfloor \frac{sum}{2} \rfloor2sum
  • mmax>sum−mmaxmmax>sum-mmaxmmax>summmax:答案为 sum−mmaxsum-mmaxsummmax
  • 第二种情况比较显然,用另外两种袜子都来和最大值所表示的袜子匹配一定是最优的,重点是需要想明白如果不等式满足了第一种情况,那么一定是存在着一种分配方案,使得所有袜子要么全匹配,要么至多只剩一只无法匹配的情况

    所以扩展到本题的情况,如果去二分答案,那么该如何去 checkcheckcheck 呢。观察上面问题的简化版,不难发现对于某种鲜花而言,大于答案的部分是没有贡献的。假设我们当前二分的答案为 midmidmid,只需要将所有鲜花的 min(mid,ai)min(mid,a_i)min(mid,ai) 求和记为 sumsumsum,就变成了上面提到的第一种情况,也就是此时可以组成 ⌊sum2⌋\lfloor \frac{sum}{2} \rfloor2sum 束鲜花,和 midmidmid 判断一下大小关系就好了

    代码:

    // Problem: Flowers // Contest: NowCoder // URL: https://ac.nowcoder.com/acm/contest/7830/J // Memory Limit: 524288 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) (x&-x) using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const LL inf=0x3f3f3f3f3f3f3f3f; const int N=1e6+100; int n,m; LL a[N]; bool check(LL mid) {LL sum=0;for(int i=1;i<=n;i++) {sum+=min(a[i],mid);}return sum/m>=mid; } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--) {read(n),read(m);for(int i=1;i<=n;i++) {read(a[i]);}LL l=0,r=inf,ans=-1;while(l<=r) {LL mid=(l+r)>>1;if(check(mid)) {ans=mid;l=mid+1;} else {r=mid-1;}}cout<<ans<<endl;}return 0; }

    总结

    以上是生活随笔为你收集整理的2019ICPC(沈阳) - Flowers(二分)的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。