题目链接:点击查看
题目大意:给出一个 n ,表示 1 ~ n 的 n 个数字,现在要求选出尽可能多的两两匹配,使得每组匹配的 gcd 都大于 1,输出最多能有多少组匹配,以及方案
题目分析:
这样的贪心策略肯定是最优的,除了 p * 2 > n 的质数和 1 ,最多会有 1 个未匹配的数,其他的数都会两两匹配
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=2e5+100;
bool p[N],vis[N];
void init()
{
for(int i=2;i<N;i++)
if(!p[i])
for(int j=i+i;j<N;j+=i)
p[j]=true;
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
init();
int w;
cin>>w;
while(w--)
{
int n;
scanf("%d",&n);
memset(vis,false,n+5);
vector<pair<int,int>>ans;
for(int i=n/2;i>=2;i--)//枚举小于等于n/2的质数
{
if(p[i])
continue;
int cnt=0;//有多少个含有质因子i且未被用过的合数
for(int j=i;j<=n;j+=i)
cnt+=!vis[j];
if(i!=2&&cnt&1)//如果有奇数个可以匹配的合数,那么将2的倍数提出来
vis[i*2]=true;
int pre=-1;
for(int j=i;j<=n;j+=i)
{
if(vis[j])
continue;
vis[j]=true;
if(pre==-1)
pre=j;
else
{
ans.emplace_back(pre,j);
pre=-1;
}
}
if(cnt&1)//回溯标记
vis[i*2]=false;
}
printf("%d\n",ans.size());
for(int i=0;i<ans.size();i++)
printf("%d %d\n",ans[i].first,ans[i].second);
}
return 0;
}