【蓝桥官网试题 - 算法提高】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 ;
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值