2023年码蹄杯三赛H题-跳跳棋 知识点:搜索,素数筛,模拟

69 阅读1分钟

码题集OJ-跳跳棋 (matiji.net)

刚开始用的试除法过不去:

#include <bits/stdc++.h>

using namespace std;
#define int long long

int n, m;
vector<vector<int>> g;
int cnt;


bool isprime(int n)
{
	if(n<2)return false;
	for(int i=2;i*i<=n;i++)
	{
		if(n%2==0)return false;
	}
return true;
}



void dfs(int x, int y)
{
	if (y >= m)
	{
		y = 0;
		x++;
	}
	if (x >= n)
	{
		return;
	}

	int value = g[x][y];
	
	if(isprime(value))
	{
	  dfs(x,y+value%10);	
	  cnt++;
	}
	else
	{
		dfs(x, y + 1);
	}
}

void solve()
{
	cin >> n >> m;

	g.assign(n, vector<int>(m, 0));
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> g[i][j];

	dfs(0, 0);

	cout << cnt;
}
signed main()
{
	cin.tie(nullptr)->sync_with_stdio(false);

		solve();
	
	return 0;
}

image.png

用埃氏筛就过去了:

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n, m;
const int N = 110;

int cnt;

const int M= 1e5 + 10;
bool book[M];
int a[110][110];
void isprime()
{
    book[0] = book[1] = true;
	for (int i = 2; i < M; i++)
	{
		for (int j = i; i * j <M; j++)
		{
			book[i * j] = true;
		}
	}
}

void dfs(int x,int y)
{
	if (y >= m)
	{
		y = 0;
		x++;
	}

	if (x >= n)
	{
		return;
	}

	int value = a[x][y];

	if (!book[value])
	{

		dfs(x,y+value%10);
		cnt++;
	}
	else
	{
		dfs(x,y+1);
	}
}



void solve()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> a[i][j];
	dfs(0, 0);
	cout << cnt;
  }
signed main()
{
    cin.tie(nullptr)->sync_with_stdio(false);
    isprime();
    solve();
    return 0;
}


#include<bits/stdc++.h>
#define int long long
using namespace std;
int n, m;
const int N = 110;

int cnt;

const int M= 1e5 + 10;
bool book[M];
int a[110][110];
void isprime()
{
    book[0] = book[1] = true;
	for (int i = 2; i < M; i++)
	{
		for (int j = i; i * j <M; j++)
		{
			book[i * j] = true;
		}
	}
}

void dfs(int x,int y)
{
	if (y >= m)
	{
		y = 0;
		x++;
	}

	if (x >= n)
	{
		return;
	}

	int value = a[x][y];

	if (!book[value])
	{

		dfs(x,y+value%10);
		cnt++;
	}
	else
	{
		dfs(x,y+1);
	}
}



void solve()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> a[i][j];
	dfs(0, 0);
	cout << cnt;
  }
signed main()
{
    cin.tie(nullptr)->sync_with_stdio(false);
    isprime();
    solve();
    return 0;
}



image.png