CodeForces - 1337D Xenia and Colorful Gems(二分)
題目鏈接:點(diǎn)擊查看
題目大意:給出三個(gè)序列分別記為 a,b,c,現(xiàn)在要求分別從三個(gè)序列中找出 x , y , z ,使得 ( x - y )^2 + ( y - z )^2 + ( y - z )^2 最小,求出這個(gè)最小值
題目分析:讀完題第一反應(yīng)就是二分嘛,稍微理了一下思路,假設(shè) x <= y <= z ,可以枚舉其中一個(gè)數(shù)組的數(shù)作為 y?,然后在另外兩個(gè)數(shù)組中,一個(gè)找到小于等于 y 的最大值記為 x ,另一個(gè)找大于等于 y 的最小值記為 z ,維護(hù)最小值就是答案了
思路非常簡(jiǎn)單,就是實(shí)現(xiàn)起來(lái)可能寫的比較惡心,這邊建議可以將函數(shù)封裝一下,然后反復(fù)調(diào)用就好了
一開始想到了 splay 里恰好就有這兩個(gè)操作,于是就想白嫖,把以前的代碼拿下來(lái)copy過去,果不其然的TLE了,難頂,然后自己寫二分過的,過了四個(gè)題之后愉快下班洗漱睡覺,在洗漱的過程中想到了 inf 可能不能作為無(wú)窮大,但自己也沒法hack掉自己,就懶得在改了,第二天早晨果不其然被fst了,不過還好是小號(hào),不然心態(tài)就崩了。。
最后補(bǔ)充一個(gè)小技巧,為了防止二分時(shí)對(duì)邊界的判斷,在每個(gè)數(shù)組中加一個(gè) -inf 和 inf 就好了,需要注意的是,因?yàn)槲业?inf 是0x3f3f3f3f ,在這個(gè)題目中不夠大,所以在計(jì)算?( x - y )^2 + ( y - z )^2 + ( y - z )^2 的函數(shù)中特判一下就行了
代碼:
#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<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=2e5+100;LL a[N],b[N],c[N];inline LL get_upper(LL a[],int n,LL x)//在數(shù)組a中找到大于等于x的最小值 {int l=0,r=n+1;LL ans;while(l<=r){int mid=l+r>>1;if(a[mid]>=x){ans=a[mid];r=mid-1;}elsel=mid+1;}return ans; }inline LL get_lower(LL a[],int n,LL x)//在數(shù)組a中找到小于等于x的最大值 {int l=0,r=n+1;LL ans;while(l<=r){int mid=l+r>>1;if(a[mid]<=x){ans=a[mid];l=mid+1;}elser=mid-1;}return ans; }inline LL fun(LL x,LL y,LL z) {if(x==inf||y==inf||z==inf)//特判infreturn LLONG_MAX;return (x-y)*(x-y)+(x-z)*(x-z)+(y-z)*(y-z); }LL cal(LL a[],int na,LL b[],int nb,LL c[],int nc)//遍歷數(shù)組a作為y {LL ans=LLONG_MAX;for(int i=1;i<=na;i++){ans=min(ans,fun(a[i],get_lower(b,nb,a[i]),get_upper(c,nc,a[i])));ans=min(ans,fun(a[i],get_upper(b,nb,a[i]),get_lower(c,nc,a[i])));}return ans; }int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--){int na,nb,nc;scanf("%d%d%d",&na,&nb,&nc);for(int i=1;i<=na;i++)scanf("%lld",a+i);for(int i=1;i<=nb;i++)scanf("%lld",b+i);for(int i=1;i<=nc;i++)scanf("%lld",c+i);a[0]=b[0]=c[0]=-inf;a[na+1]=b[nb+1]=c[nc+1]=inf;sort(a+1,a+1+na);sort(b+1,b+1+nb);sort(c+1,c+1+nc);printf("%lld\n",min(cal(c,nc,a,na,b,nb),min(cal(a,na,b,nb,c,nc),cal(b,nb,a,na,c,nc))));}return 0; }?
總結(jié)
以上是生活随笔為你收集整理的CodeForces - 1337D Xenia and Colorful Gems(二分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1337E K
- 下一篇: CodeForces - 1337C L