CF - 271B Prime Matrix

Problem Description

You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.

You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.

A matrix is prime if at least one of the two following conditions fulfills:

    the matrix has a row with prime numbers only;
    the matrix has a column with prime numbers only;

Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.

 

 Input

The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly.

Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105.

The numbers in the lines are separated by single spaces.

 

Output 

Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.

 

Examples 

input
3 3
1 2 3
5 6 1
4 4 1
output
1
input
2 3
4 8 8
9 2 9
output
3
input
2 2
1 3
4 2
output
0

 

解题说明:

题目中一个素数矩阵的要求是只有一行元素都是素数,或只有一列元素都是素数。这里可以找出矩阵中所有元素与其最接近的素数直接的差值(素数要比该元素大才行),然后针对每一行,每一列求出一个差值最小的。为此,需要先存储一个较大的素数数组,这个可以预先计算出来。考虑到矩阵中元素的值不会超过10^5,那素数数组的大小也就是这个数量级即可。最后找出一列或一行差值最小的输出。

 

素数打表的时候用到了线性筛  (可以在O(n)的时间内找到所有素数)  这是素数打表最高效的方法。

 

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int prime[100010],map[510][510];
int sumc[510],sumr[510];
int tag[100010];
int cnt;
void Prime(){   //线性筛
	memset(tag,0,sizeof(tag));
	cnt=0;
	tag[0]=tag[1]=1;
	for(int i = 2; i<100010; i++){
		if(!tag[i])
			prime[cnt++]=i;
		for(int j=0;j<cnt && prime[j]*i<100010; j++){
			tag[i*prime[j]] = 1;
			if(i % prime[j]==0)
				break;
		}
	}
}

int main()
{
	int n,m,i,j,k;
	scanf("%d%d",&n,&m);
	Prime();
	memset(map,0,sizeof(map));
	memset(sumc,0,sizeof(sumc));
	memset(sumr,0,sizeof(sumr));
	for(i=0;i<n;i++)
	for(j=0;j<m;j++)
	{
		scanf("%d",&map[i][j]);
	}
	for(i=0;i<n;i++)
	{
		int sum=0;
		for(j=0;j<m;j++)
		{
			if(tag[map[i][j]])//如果输入的数不是素数
			{
				int t=lower_bound(prime,prime+cnt,map[i][j])-prime;
				sumr[j]+=(prime[t]-map[i][j]);
				sumc[i]+=(prime[t]-map[i][j]);
			 }
		}
	}

	sort(sumr,sumr+m);
	sort(sumc,sumc+n);
	cout<<((sumr[0]<sumc[0])?sumr[0]:sumc[0])<<endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值