欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

牛客多校4 - Harder Gcd Problem(构造+贪心)

发布时间:2024/4/11 编程问答 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 牛客多校4 - Harder Gcd Problem(构造+贪心) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目链接:点击查看

题目大意:给出一个 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; }

 

总结

以上是生活随笔为你收集整理的牛客多校4 - Harder Gcd Problem(构造+贪心)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。