题解 | #素数伴侣#

素数伴侣

http://www.nowcoder.com/practice/b9eae162e02f4f928eac37d7699b352e

#include <stdio.h>
#include <string.h>
#include <math.h>
int match(int even[], int odd[], int i, int odd_count, int vis[], int p[]);
int isprime(int n);

int main()
{
  int n;
  while (scanf("%d", &n) != EOF)
  {
    int num;
    int even[n], odd[n];
    int even_count = 0, odd_count = 0;
    for (int i = 0; i < n; i++)
    {
      scanf("%d", &num);
      if (num % 2 == 0)
        even[even_count++] = num;
      else
        odd[odd_count++] = num;
    }
    //0-even_count-1
    int vis[odd_count];
    int p[odd_count];
    for (int i = 0; i < odd_count; i++)
    {
      vis[i] = 0;
      p[i] = -1;
    }
    int cnt = 0;
    for (int i = 0; i < even_count; i++)
    {
      memset(vis, 0, sizeof(vis));
      if (match(even, odd, i, odd_count, vis, p))
        cnt++;
    }
    printf("%d\n", cnt);
  }

  return 0;
}

int match(int even[], int odd[], int i, int odd_count, int vis[], int p[])
{

  for (int j = 0; j < odd_count; j++)
  {
    if (vis[j] == 0 && isprime(even[i] + odd[j]))
    {
      vis[j]=1;
      if (p[j] < 0 || match(even, odd, p[j], odd_count, vis, p))
      {
        p[j] = i;
        return 1;
      }
    }
  }

  return 0;
}

int isprime(int n)
{
  int ret = 1;
  if (n == 1 || (n % 2 == 0 && n != 2))
    ret = 0;
  else
  {
    for (int i = 3; i <= sqrt(n); i += 2)
      if (n % i == 0)
      {
        ret = 0;
        break;
      }
  }
  return ret;
}
全部评论

相关推荐

10-09 09:39
门头沟学院 C++
HHHHaos:这也太虚了,工资就一半是真的
点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务