sgu116:Index of super-prime

先用oula筛出所有的super_prime数,再BFS检查是否有解

第一次写STL感觉不习惯呐

代码如下(囧):

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;

const int MAXN = 10030;
int su_pr[MAXN] = {0}, tot = 0;
int N;

void oula()
{
  int prime[MAXN] = {0}, top = 0;
  bool hash[MAXN] = {0};
  memset(hash, true, sizeof(hash));
  hash[1] = false;
  for(int i = 2; i <= N; ++i)
  {
	if(hash[i]) 
	{
	  prime[++top] = i;
	  if(hash[top]) 
	    su_pr[++tot] = i;
    }
    for(int j = 1; j <= top && prime[j] * i <= N; ++j)
    {
      hash[prime[j] * i] = false;	
      if(prime[j] % i == 0) break;
    }
  }
}

queue<int> q;
vector<int> father, state, step;

void print(int r)
{
  if(r > 0) print(father[r]);	
  else return ;
  cout << state[r] << ' ';
}

bool work()
{  
  bool hash[MAXN] = {false};
  int l = -1, r = 0;
  father.push_back(0);
  state.push_back(0);
  step.push_back(0);
  q.push(0);
  hash[0] = true;
  while(!q.empty())
  {
	int v = q.front();
	q.pop();
	l++;
	for(int i = tot; i >= 1; --i) 
	  if(v + su_pr[i] <= N && !hash[v + su_pr[i]])	
	  {
	  	r++;
		hash[v + su_pr[i]] = true;
		father.push_back(l);
		state.push_back(su_pr[i]);
		step.push_back(step[l] + 1);
		q.push(v + su_pr[i]);
		if(v + su_pr[i] == N)
		{
		  cout << step[r] << '\n';
		  print(r);
		  return true;	
		}
	  }
  }
  return false;
}

int main()
{
  cin >> N;
  oula();
  if(!work()) cout << '0';
  return 0;	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值