【蓝桥官网试题 - 算法提高】change(思维)
生活随笔
收集整理的這篇文章主要介紹了
【蓝桥官网试题 - 算法提高】change(思维)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題干:
問題描述
數組A中共有n個元素,初始全為0。你可以對數組進行兩種操作:1、將數組中的一個元素加1;2、將數組中所有元素乘2。求將數組A從初始狀態變為目標狀態B所需要的最少操作數。
輸入格式
第一行一個正整數n表示數組中元素的個數
第二行n個正整數表示目標狀態B中的元素
輸出格式
輸出一行表示最少操作數
樣例輸入
2
7 8
樣例輸出
7
數據規模和約定
n<=50,B[i]<=1000
?
解題報告:
? 一眼bfs,,再讀題發現不能這樣做,,乘2操作是全數組一起的,,然后倒著做一下就出來了。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; int a[MAX],n; bool ok() {for(int i = 1; i<=n; i++) {if(a[i]!=0) return 1;}return 0 ; } bool allou() {for(int i = 1; i<=n; i++) {if(a[i]&1) return 0 ;}return 1 ; } int main() {cin>>n;int ans = 0;for(int i = 1; i<=n; i++) scanf("%d",a+i);while(ok()) {if(allou()) {ans++;for(int i = 1; i<=n; i++) a[i]/=2;continue;}for(int i = 1; i<=n; i++) {if(a[i]&1) ans++,a[i]--;}}cout << ans;return 0 ;}錯誤代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; int a[MAX],ans2[MAX]; struct Node {ll v;int step;int jia,ch; Node(){}Node(ll v,int step,int jia,int ch):v(v),step(step),jia(jia),ch(ch){} }; Node bfs(ll a,ll b) {queue<Node> q;q.push(Node(a,0,0,0));while(q.size()) {Node cur = q.front();q.pop();if(cur.v == b) return cur;ll nowv = cur.v+1;if(nowv <= b*2) q.push(Node(nowv,cur.step+1,cur.jia+1,cur.ch));nowv = cur.v*2;if(nowv <= b*2) q.push(Node(nowv,cur.step+1,cur.jia,cur.ch+1)); }return Node(0,0,0,0); } int main() {int n;int ans1=0;cin>>n;for(int i = 1; i<=n; i++) {scanf("%d",a+i);Node res = bfs(0,1ll*a[i]);ans1 += res.jia;ans2[i] = res.ch;}int tmp = *min_element(ans2+1,ans2+n+1);for(int i = 1; i<=n; i++) {ans1 += (ans2[i] - tmp) * 2;}printf("%d\n",ans1+tmp);return 0 ;}?
總結
以上是生活随笔為你收集整理的【蓝桥官网试题 - 算法提高】change(思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 平安信用卡审核要多久 网络申请秒批也有可
- 下一篇: 【Gym - 101915D】Large