CodeForces - 1360H Binary Median(二分)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1360H Binary Median(二分)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n 和 m ,初始時集合中含有 0 ~ 2^m - 1 共 2^m 個數,隨后從中刪去 n 個數,現在需要此時集合中的中位數
題目分析:一開始被字典序迷惑了,仔細想了一下發現,其實二進制下的字典序,和普通的排序沒有區別,且 m 最大才為 60 ,所以可以將字符串轉換為整數從而進行二分,因為多了刪除這個條件,我們需要設計一下 check 函數然后尋找一下單調性
設中位數為 k ,換句話說我們需要找到集合中第 k 大的那個數,可以二分 mid ,每次遍歷一遍這 n 個數,計算有多少個數小于等于mid 記為 cnt ,那么此時 mid 所代表的數就是第 mid - cnt 小的了,觀察一下單調性:
以第二個樣例為例,觀察一下單調性,最上面一行的紅色數字代表當前的數在數列中是第幾小,可以分類討論一下如何二分:
然后實現就好了
代碼:
#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<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=110;LL a[N];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 n,m;scanf("%d%d",&n,&m);for(int i=1;i<=n;i++){string s;cin>>s;a[i]=0;for(int j=0;j<m;j++)a[i]=a[i]*2+(s[j]-'0');}LL mark=((1LL<<m)-n-1)/2;LL l=0,r=(1LL<<m)-1,ans;while(l<=r){LL mid=l+r>>1;int cnt=0;for(int i=1;i<=n;i++)if(mid>=a[i])cnt++;if(mid-cnt>=mark){ans=mid;r=mid-1;}elsel=mid+1;}for(int i=m-1;i>=0;i--)printf("%d",(ans>>i)&1);puts("");}return 0; }?
總結
以上是生活随笔為你收集整理的CodeForces - 1360H Binary Median(二分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1360G A
- 下一篇: 牛客 - 交换(思维+找循环节)