CodeForces - 1303D Fill The Bag(贪心+模拟)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1303D Fill The Bag(贪心+模拟)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個背包,容量為 k ,再給出 n 個物品,每個物品的大小保證是 2 的冪次,現在可以進行操作,使得一個物品分為大小相等的,且大小等于原物品一半的兩個物品,比如一個物品原來為 4 ,可以分為兩個 2 ,現在問最少需要操作多少次,才能讓物品恰好裝滿背包
題目分析:因為題目提示的很明顯了,給出的物品以及操作都是對于 2 的冪次進行操作,所以可以將背包容量 k 進行二進制分解,然后從最低位開始貪心填滿即可,如果當前位置有物品的話,直接用這個物品填滿,如果沒有物品的話,就必須要找到首個大于當前位置的物品進行拆分,知道這個貪心策略后剩下的就是模擬了
代碼:
#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=1e5+100;int a[N],cnt[100];int get_num(int num)//返回當前的數字為2的多少次冪 {int ans=0;while(num){ans++;num>>=1;}return ans-1; } 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--){memset(cnt,0,sizeof(cnt));LL n,m;scanf("%lld%lld",&n,&m);LL sum=0;for(int i=1;i<=m;i++){scanf("%d",a+i);cnt[get_num(a[i])]++;//統計每個物品,轉換成2的冪次sum+=a[i];}if(sum<n)//特判-1{printf("-1\n");continue;}vector<int>bit;while(n)//將背包容量轉換為二進制{bit.push_back(n%2);n>>=1;}int ans=0;for(int i=0;i<bit.size();i++)//從最低位開始貪心{if(bit[i])//如果此位需要物品裝填{int pos=i;if(!cnt[pos])//如果當前位置沒有物品,則向上尋找{while(!cnt[pos]){cnt[pos]++;pos++;ans++;}cnt[pos]--;//被分解的物品需要減一cnt[i]++;//最低位需要加一}cnt[i]--;//直接使用物品填補背包}cnt[i+1]+=cnt[i]/2;//用較低的位更新較高的位}printf("%d\n",ans);}return 0; }?
總結
以上是生活随笔為你收集整理的CodeForces - 1303D Fill The Bag(贪心+模拟)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU - 4416 Good Arti
- 下一篇: CodeForces - 1303E E