1. 程式人生 > 實用技巧 >E1. Asterism (Easy Version) 暴力+二分求方案

E1. Asterism (Easy Version) 暴力+二分求方案

https://blog.csdn.net/Joker_He/article/details/107087092

題意: 假設你有x顆糖果,你面前有n個敵人,第i個敵人有a[i]顆糖果,你可以選擇對戰的順序,如果你手裡的糖果不比敵人少,那麼你勝利並獲得一顆糖果,現在我們定義f(x)為你手裡有x顆糖果時,你能打敗所有對手的方案數,對於給定質數p,如果f(x)與p互質,那麼這個x就是符合要求的,現在給定n,p和a[i],問你有多少個x符合條件,並且輸出這些x。

資料範圍:
2<=p<=n<=2000,a[i]<=2000

思路: 顯然,如果x比2000要大的話,如果這個x合法,那麼所有大於x的都合法了,這顯然就有無限個x合法了,所以可以把x的範圍控制在2000以內,那麼我們先對a[i]排序,在2000以內列舉x,用cnt表示已經戰勝的敵人,我們每次就二分查詢a陣列中小於x+cnt的數量num,num-cnt就是目前沒有交戰的敵人數量,那麼方案數是要乘num-cnt的,所以如果num-cnt是p的倍數,就可以直接break了,至於f(x)是多少,我們並不care,(如果一直乘,最後對p取模,c++的long long可能存不下而且時間複雜度也高)。最後只需要判斷是否合法並存儲答案就行了。

————————————————
版權宣告:本文為CSDN博主「Joker_He」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/Joker_He/article/details/107087092

 1 #include<bits/stdc++.h>
 2 #pragma GCC optimize("Ofast")
 3 #define
endl '\n' 4 #define null NULL 5 #define ls p<<1 6 #define rs p<<1|1 7 #define fi first 8 #define se second 9 #define mp make_pair 10 #define pb push_back 11 #define ll long long 12 #define int long long 13 #define pii pair<int,int> 14 #define ull unsigned long long 15 #define
all(x) x.begin(),x.end() 16 #define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); 17 #define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n"; 18 char *fs,*ft,buf[1<<20]; 19 #define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++; 20 inline int read(){int x=0,f=1;char ch=gc(); 21 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();} 22 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=gc();} 23 return x*f;} 24 using namespace std; 25 const int N=2e5+5; 26 const int inf=0x3f3f3f3f; 27 const int mod=1e9+7; 28 const double eps=1e-7; 29 const double PI=acos(-1); 30 int a[N]; 31 signed main() 32 { 33 int n,p; 34 cin>>n>>p; 35 for(int i=1;i<=n;i++) 36 cin>>a[i]; 37 sort(a+1,a+n+1); 38 vector<int>v; 39 for(int i=1;i<=2000;i++){ 40 int cnt=0,res=0,fg=1; 41 for(int j=1;j<=n;j++){ 42 int pos=upper_bound(a+1,a+n+1,i+cnt)-a; 43 pos--; 44 if((pos-cnt)%p==0) 45 { 46 fg=0; 47 break; 48 } 49 cnt++; 50 } 51 if(fg) 52 v.pb(i); 53 } 54 cout<<v.size()<<endl; 55 for(auto i:v) 56 cout<<i<<' '; 57 }