AtCoder Beginner Contest 276-D
D——Divide by 2 or 3
题目链接:https://atcoder.jp/contests/abc276/tasks/abc276_d
题目说了一个什么事呢,其实就是给你n个数字,你可以执行相应的操作——如果数字是2的倍数,可以将该数字除以2;如果数字是3的倍数,可以将该数字除以3。
那么问你的就是你能不能通过一定的操作令所有的数都相同,如果可以,找到所需最小的操作数。
问题其实很简单,自己刚开始做的时候想复杂了。
其实我们可以先找所有数字的最大公因数a,a就是我们完成所有操作后数组元素相等的那个数(为啥呢?我觉得吧,将每一个数都拆分成2和3和一个其他的数的乘积就能理解了),然后将所有的元素都进行除2除3的操作,尝试将其化为a。如果尝试的过程中不能化成a,那么它的因子里面就存在着除了2、3、a以外的其他因子,那么它就是数组里不能满足要求的元素,输出-1;没有这种情况出现时,给定的数组可以满足题目的要求,统计一下除2和除3的次数即可。
多说无益,上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<cmath> #include<map> #include<vector> #define ll long long #define ull unsigned long long #define mem(x,y) memset(x,y,sizeof(x)) //#define int long long inline ll read() { ll x=0,f=1; char ch= getchar (); while (ch< '0' ||ch> '9' ){ if (ch== '-' ) f=-1;ch= getchar ();} while (ch>= '0' &&ch<= '9' ){x=x*10+ch-48;ch= getchar ();} return x*f; } int gcd( int a, int b){ int t; if (a<b) {t=a;a=b;b=t;} if (b==0) return a; else return gcd(b,a%b); } using namespace std; const int maxm=1e3+5,inf=0x3f3f3f3f; int n,a[maxm]; void solve(){ cin>>n; int r=0,cnt=0; for ( int i=0;i<n;++i){ cin>>a[i]; r=gcd(a[i],r); } for ( int i=0;i<n;++i){ a[i]/=r; while (a[i]%2==0){ a[i]/=2; ++cnt; } while (a[i]%3==0){ a[i]/=3; ++cnt; } if (a[i]!=1){ cout<<-1<<endl; return ; } } // cout<<r<<endl; cout<<cnt<<endl; return ; } signed main(){ // ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); int _=1; // cin>>_; while (_--){ solve(); } return 0; } |
本文来自博客园,作者:Qiansui,转载请注明原文链接:https://www.cnblogs.com/Qiansui/p/16861517.html
分类:
oj - Atcoder
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】