题目大意:一个A序列,让你求一个B序列,满足
ai<ai+1 bi<bi+1
ai>ai+1 bi>bi+1
ai=ai+1 bi≠bi+1
并且1<=bi<=5 问是否有这样的B序列。
思路一:贪心 要根据3个相邻的数来贪
首先几种情况
① ai-1ai
1. aiai+1 那么ai就取2或3
2. ai<ai+1 那么ai就取最小的1,如果前一个为1就取2
3. ai>ai+1 同理取5或者4
②ai-1<ai
1.ai>ai+1 此时ai为波峰,能取5就为5,否则为4
2.其他取 ai-1数值+1
③ai-1>ai
1.ai<ai+1 ai为波谷,能取1为1,否则为2
2,其他取ai-1数值-1;
取完之后判断数据是否在范围中,否则输出-1
#include<bits/stdc++.h>
#define fi first
#define se second
#define FOR(a) for(int i=0;i<a;i++)
#define sc(a) scanf("%d",&a)
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, int> LP;
const ll inf = 1e17 + 10;
const int N = 2e5 + 10;
const ll mod = 998244353;
map<string, int>ml;
ll c[N], vis[N], num[N], t, n, m, x, y, k, a[N];
char s[N];
ll ex, ey, cnt, ans;
ll dist[N];
ll dp[5000][5000];
deque <int> q;
struct node
{
int up,down;
} v[N];
int main()
{
//for(int i=1;i<=74;i++)
// cout<<"a";
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
if(a[1]<a[2]) num[1]=1;
else if(a[1]==a[2]) num[1]=3;
else num[1]=5;
for(int i=2;i<=n;i++)
{
if(a[i-1]==a[i])
{
if(a[i]==a[i+1]) num[i]=num[i-1]!=3?3:2;
else if(a[i]<a[i+1]) num[i]=num[i-1]!=1?1:2;
else num[i]=num[i-1]!=5?5:4;
}
else if(a[i]>a[i-1])
{
if(a[i]>a[i+1]) num[i]=num[i-1]!=5?5:num[i-1]+1;
else num[i]=num[i-1]+1;
}
else if(a[i]<a[i-1])
{
if(a[i]<a[i+1]) num[i]=num[i-1]!=1?1:num[i-1]-1;
else num[i]=num[i-1]-1;
}
if(num[i]<1||num[i]>5) return cout<<-1<<endl,0;
}
for(int i=1;i<=n;i++) cout<<num[i]<<" ";
}
dfs:直接将第一个数值赋值1~5,然后暴力搜索满足条件的序列输出就行了
#include<bits/stdc++.h>
#define fi first
#define se second
#define FOR(a) for(int i=0;i<a;i++)
#define sc(a) scanf("%d",&a)
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, int> LP;
const ll inf = 1e17 + 10;
const int N = 2e5 + 10;
const ll mod = 998244353;
map<string, int>ml;
ll c[N], vis[N][10], num[N], t, n, m, x, y, k, a[N];
char s[N];
ll ex, ey, cnt, ans;
ll dist[N];
ll dp[N][10];
deque <int> q;
struct node
{
int up,down;
} v[N];
bool dfs(int x)
{
if(x==n) return 1;
for(int i=1;i<=5;i++)
{
if(!vis[x+1][i])
{
if((a[x+1]==a[x]&&num[x]!=i)||(a[x+1]>a[x]&&i>num[x])||(a[x+1]<a[x]&&i<num[x]))
{
num[x+1]=i;
vis[x+1][i]=1;
if(dfs(x+1))return 1;
}
}
}
return 0;
}
int main()
{
//for(int i=1;i<=74;i++)
// cout<<"a";
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=1;i<=5;i++)
{
num[1]=i;
if(dfs(1))
{
t=1;
break;
}
}
if(!t) return cout<<-1<<endl,0;
for(int i=1;i<=n;i++) cout<<num[i]<<" ";
}