A - Romaji CodeForces - 1008A
B - Turn the Rectangles CodeForces - 1008B
C - Reorder the Array CodeForces - 1008C
D - Saving Snuuk AtCoder - 4190
E - + Graph AtCoder - 4191 (留坑,至今未果,寻病终)
A
题目简述:
把一个数组分成连续的k段,每一段的价值为这一段最大元素的值,求每一段价值之和的最大值。并输出每一段的长度。
分析:
贪心地思考一下,这个数组无论如何都可以分成k段(n>=k)则将这个数组前k大的数字分在k个部分中 问题就在于怎么输出 细节考虑比较多 考试的时候实现得不是很好 也卡了很久
//考试的实现
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAXN 2005
int N,K,ans,cn;
struct node{
int v,p;
}a[MAXN],c[MAXN];
int b[MAXN];
bool cmp(node x,node y)
{
return x.v>y.v;
}
bool cmp2(node x,node y)
{
return x.p<y.p;
}
int main()
{
scanf("%d %d",&N,&K);
for(int i=1;i<=N;i++)
{
scanf("%d",&a[i].v);
a[i].p=i;
b[i]=a[i].v;
}
sort(a+1,a+N+1,cmp);
for(int i=1;i<=K;i++)
{
ans+=a[i].v;
c[++cn].v=a[i].v;
c[cn].p=a[i].p;
}
sort(c+1,c+cn+1,cmp2);
int n=1;
printf("%d\n",ans);
int last=0;
for(int i=1;i<=N;i++)
if(b[i]==c[n].v)
{
if(n==cn)
{
printf("%d",N-last);
return 0;
}
printf("%d ",i-last);
last=i;
n++;
}
}
就是保存了前k大的数在数组中的位置,输出的时候以此分节,但却是实现不够优秀(包括最后的for循环其实多余了 都已经存有了位置 for 1~k 就OK)。
//更优秀的实现
#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN = 2000;
struct node{
int val, id;
}a[MAXN + 5];
bool operator < (node a, node b) {
return a.val < b.val;
}
int b[MAXN + 5], bcnt;
int main() {
int n, k;