C 忽远忽近的距离【2023牛客寒假算法基础集训营3 】
C 忽远忽近的距离
题意
1。构造一个长度为n的排列,使得满足对于每个
思路1(dfs枚举)
- 对于每个
都有
- 当
时 - 当
时 - 因此
可能的取值为 【偏移量】
代码1
点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define X first
#define Y second
typedef long long LL;
const char nl = '\n';
int n;
const int N = 1e5 + 10;
int a[N],d[N];
int dx[]={-2,-3,2,3}; //偏移量
bool f = 0;
void dfs(int x){
if(x > n && !f){ //如果第一次枚举到n+1位
for(int i = 1; i <= n; i ++ )cout << a[i] << " ";
cout << nl;
f = 1;
return;
}
for(int i = 0; i <= 3; i ++ ){
if(f)break; //只需要一个答案
int u = x + dx[i];
if(u <= 0 || u > n || d[u])continue;
d[u] = 1; //每个数只能用一次
a[x] = u;
dfs(x+1);
d[u] = 0;
//a[x] = 0; //后面会被覆盖掉
}
}
void solve(){
cin >> n;
dfs(1);
if(!f)cout << -1;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
solve();
}
思路2(模块化构造)
我们从样例可以发现,
之后我们可以尝试构造
例如
代码2
点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define X first
#define Y second
typedef long long LL;
const char nl = '\n';
const int N = 1e6+10;
int n,m;
int d4[]={3,4,1,2},d5[]={4,5,1,2,3},d6[]={4,5,6,1,2,3};
void solve(){
cin >> n;
int t = n % 4;
if(n < 4 || n == 7)cout << -1;
else if(t == 0){
for(int i = 0; i < n / 4; i ++)
for(int j = 0; j < 4; j ++)
cout << d4[j] + 4 * i << " ";
}
else if(t == 1){
for(int i = 0; i < n / 4 -1; i ++)
for(int j = 0; j < 4; j ++)
cout << d4[j] + 4 * i << " ";
for(int j = 0; j < 5; j ++)cout << d5[j] + n - 5 << " ";
}
else if(t == 2){
for(int i = 0; i < n / 4 -1; i ++)
for(int j = 0; j < 4; j ++)
cout << d4[j] + 4 * i << " ";
for(int j = 0; j < 6; j ++)cout << d6[j] + n - 6 << " ";
}
else{
for(int i = 0; i < n / 4 -2; i ++)
for(int j = 0; j < 4; j ++)
cout << d4[j] + 4 * i << " ";
for(int j = 0; j < 5; j ++)cout << d5[j] + n - 5 - 6 << " ";
for(int j = 0; j < 6; j ++)cout << d6[j] + n - 6 << " ";
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
solve();
}
标签:
2023牛客寒假算法基础集训营
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】