codeforces891a
2 seconds
256 megabytes
standard input
standard output
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.
5
2 2 3 4 6
5
4
2 4 6 8
-1
3
2 6 9
4
In the first sample you can turn all numbers to 1 using the following 5 moves:
- [2, 2, 3, 4, 6].
- [2, 1, 3, 4, 6]
- [2, 1, 3, 1, 6]
- [2, 1, 1, 1, 6]
- [1, 1, 1, 1, 6]
- [1, 1, 1, 1, 1]
We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
这个题很简单,就是找一下那个公约数为1
看测试样例1:
2 2 3 4 6
先求他的第一层公约数就是2和2,2和3,3和4,4和6求公约数
2 2 3 4 6
2 1 1 2
这时候发现有1的存在
答案就是 当前的层数-1+n-1 (n就是几个数) 因为有一个1就能把所有的都变成1
注意特判
2
1 1
这种的
丑陋的代码:
#include <iostream>
#include <cstdio>
using namespace std;
long long arr[2005][2005];
long long gcd(long long a,long long b);
int main()
{
long long n,i,j;
int flag = 0;
scanf("%lld",&n);
for(i = 0; i < n; ++i) {
scanf("%lld",arr[0]+i);
if(arr[0][i] == 1)
flag ++;
}
if(flag) {
printf("%lld\n",n-flag);
return 0;
}
for(i = 1; i <= n-1; ++i)
{
for(j = 0; j < n - i; ++j)
{
arr[i][j] = gcd(arr[i-1][j], arr[i-1][j+1]);
if(arr[i][j] == 1) {
printf("%lld\n",i+n-1);
return 0;
}
}
}
printf("-1\n");
}
long long gcd(long long a,long long b)
{
return b == 0?a:gcd(b,a%b);
}
codeforces891a的更多相关文章
随机推荐
- 使用GrabCut提取前景图像的示范代码
#include<opencv2/opencv.hpp> bool selectObject = false; cv::Point origin; cv::Rect selection; ...
- PHP 文件操作代码
<?php //echo filetype("./1.jpg"); //判断文件类型 文件:file //echo filetype("./code"); ...
- HTTP.ResponseCode
HTTP响应码: http://blog.csdn.net/cutbug/article/details/4024818
- 0 or 1,1 and 0
最近小编遇到很头疼的的一件事 就是以下这几道运算题 ,以下结果是小编经过大量的运算得出的 一.或运算 1.0 or 1 结果为:1 2.1 or 0 结果为:1 3.1 or 2 结果为:1 4.2 ...
- Maximum Product Subarray LT152
Given an integer array nums, find the contiguous subarray within an array (containing at least one n ...
- 用 Python 写 Robot Framework 测试
Robot Framework 框架是基于 Python 语言开发的,所以,它本质上是 Python 的一个库. 1.你懂 Python 语言. 2.又想使用 Robot Framework 测试框架 ...
- 使用Apache CXF和Spring集成创建Web Service(zz)
使用Apache CXF和Spring集成创建Web Service 您的评价: 还行 收藏该经验 1.创建HelloWorld 接口类 查看源码 打印? 1 package ...
- 2016年3月31日_应化所群体Review
Review目的: Phonegap的ble插件可以接收到设备发送的信息,但接收并在控制台显示的数据夏一鸣不知道是正确的数据,还是由于编码解码问题导致的乱码问题.此次Review要解决的问题即判断接收 ...
- 【Linux】开机自动启动脚本
Linux下(以RedHat为范本)添加开机开机自动启动脚本有两种方式; 本例系统:Linux(CentOS 7.2) 方法一 使用 /etc/rc.d/rc.local,自动启动脚本 #!/bin/ ...
- ManageEngine的EventLog Analyzer许可信息