Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 105).
Print n integers forming the permutation. If there are multiple answers, print any of them.
3 2
1 3 2
3 1
1 2 3
5 2
1 3 2 4 5
By |x| we denote the absolute value of number x.
构造题。
我们首先让序列有k-1个不同的,然后剩下全是1即可。
如何有k-1个不同的?
一头一尾即可~
比如n=10 那么1,10,2,9,3,8.....
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
int n,k;
scanf("%d%d",&n,&k);
int la=1,l=1,r=n+1,now=n-1;
cout<<l;
for (int i=1;i<k;i++)
{
if ((i&1)==0)
{
l=r-now;
now--;
la=l;
cout<<" "<<l;
}
else
{
r=l+now;
la=r;
cout<<" "<<r;
now--;
}
}
if (la==l)
{
for (int i=la+1;i<r;i++)
cout<<" "<<i;
}
else
{
for (int i=la-1;i>l;i--)
cout<<" "<<i;
}
cout<<endl;
return 0;
}
每一位分别做。
这道题一定要考虑清楚再写!!
枚举每一位,如果一个区间的这一位为1,那么这一段必须全是1;如果这一位是0,那么这个区间至少有一个0。
我们先把必须是1的赋值为1,用前缀和判断是否有0即可。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#define M 100000+5
using namespace std;
struct data
{
int l,r,q;
}a[M];
int n,c[M][35],m,sum[M],ans[M][36];
bool cmp(data a,data b)
{
if (a.l==b.l) return a.r<b.r;
return a.l<b.l;
}
void Prepare()
{
memset(c,0,sizeof(c));
for (int i=1;i<=m;i++)
{
int x=a[i].q;
while (x)
{
c[i][0]++;
c[i][c[i][0]]=x&1;
x>>=1;
}
}
}
void Print()
{
for (int i=1;i<=n;i++)
{
if (!ans[i][0]) printf("0 ");
else
{
int x=0,b=1;
for (int j=1;j<=ans[i][0];j++)
{
x=x+b*ans[i][j];
b*=2;
}
printf("%d ",x);
}
}
cout<<endl;
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&a[i].l,&a[i].r,&a[i].q);
}
sort(a+1,a+1+m,cmp);
Prepare();
for (int i=1;i<=n;i++)
ans[i][0]=0;
a[0].r=0;
int f=1,now=0;
for (int i=1;i<=30;i++)
{
for (int j=0;j<=n;j++)
sum[j]=0;
for (int j=1;j<=m;j++)
{
if (c[j][i])
{
for (int k=max(a[j].l,now);k<=a[j].r;k++)
sum[k]=1,ans[k][i]=1,ans[k][0]=i;
now=max(a[j].r+1,now);
}
}
for (int j=2;j<=n;j++)
sum[j]+=sum[j-1];
now=0;
for (int j=1;j<=m;j++)
{
if (!c[j][i])
{
if (sum[a[j].r]-sum[a[j].l-1]==a[j].r-a[j].l+1)
f=0;
}
}
if (!f) break;
}
if (f) puts("YES"),Print();
else puts("NO");
return 0;
}