CF#446 Pride(水暴力)
来源:互联网 发布:80端口改变如何恢复 编辑:程序博客网 时间:2024/04/29 02:22
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say xand y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.
What is the minimum number of operations you need to make all of the elements equal to 1?
The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array.
The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.
Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.
52 2 3 4 6
5
42 4 6 8
-1
32 6 9
4
In the first sample you can turn all numbers to 1 using the following 5 moves:
题意:一列数,每次可以取两个相邻数并且把其中一个变成最大公约数,问多少次可以使数列全为1,不能全为1输出-1.
思路:因为每次只能变化一个数,所以如果初始数列就有m个1,那么就只需操作n-m次,如果没有我们可以暴力求解每个数去和相邻数运算多少次可以出现1,然后用那个1去和其他元素运算即可.
#include<cstdio>#include<iostream>#include<algorithm>#include<queue>#include<stack>#include<cstring>#include<string>#include<vector>#include<cmath> #include<map>#define mem(a,b) memset(a,b,sizeof(a))using namespace std;typedef long long ll;const int maxn = 1e6+5;const int ff = 0x3f3f3f3f;int n;int a[5200];int gcd(int x,int y){if(x< y)x = x^y,y = x^y,x = x^y;return x%y == 0?y:gcd(y,x%y);}int main(){cin>>n;int cnt = 0;for(int i = 1;i<= n;i++){scanf("%d",&a[i]);if(a[i] == 1)cnt++;}if(cnt){cout<<n-cnt<<endl;return 0;}int mint = ff;for(int i = 1;i<= n;i++){int x = a[i];cnt = 0;for(int j = i+1;j<= n;j++){cnt++;x = gcd(x,a[j]);if(x == 1)break;}if(x == 1)mint = min(mint,cnt);}if(mint == ff)cout<<-1<<endl;elsecout<<mint+n-1<<endl;return 0;}
- CF#446 Pride(水暴力)
- CodeForce Round 446 Pride
- cf 435C 暴力
- CF 557C 暴力
- CF 552E 暴力
- cf 55A(暴力 )
- cf 488 B(暴力)
- CF#305-B. Mike and Fun-暴力模拟水题
- cf 345-B - Beautiful Paintings 暴力什么的太水了
- Codeforces Round #446 (Div. 2) C.Pride
- Codeforces Round #446 (Div. 2) C Pride
- Codeforces Round #446(div 2) C. Pride
- Codeforces Round #446 (Div. 2) C. Pride
- Codeforces Round #446 (Div. 2)C. Pride
- POJ 1828 Monkeys' Pride(水~)
- cf-348A 二分暴力
- cf 551B 暴力枚举
- CF 558C 暴力,bfs
- SQL之事务
- 王者荣耀高并发背后的故事
- 随机点名demo
- Python网络爬虫学习笔记(一)
- Dev-Cpp中[Error] ld returned 1 exit status和.exe: Permission denied问题
- CF#446 Pride(水暴力)
- (九)、Java复习笔记之 I/O 流(3)
- 代码安全审查CxEnterprise
- Linux下忘记mysql密码重置方法
- 【磁盘】装系统前最好先碎片整理(机械硬盘)
- 学习随笔
- 管理系统存储
- 我的电路实践
- 从零开始前端学习[54]:js中自定义标签属性和自定义属性