2019-9 小明种苹果(续)
ccf csp刷题记录,方法不一定是最好的,只是多提供一种解题的思路和方法。
题目:
源代码:
#include<iostream>
using namespace std;
struct aptree {
int *cutnum; //new出一个空间来记录每一轮疏掉的苹果数量
int total; //该苹果树经过疏果后剩下的果子总量
int dropapple = 0;
};
int treenums;
int f(int a)
{
return a <=treenums ? a : (a - treenums);
}
int main()
{
cin >> treenums;
int turns;
int init, cutnums;
int totalcut = 0;
int totalnum = 0;
aptree *ap;
ap = new aptree[treenums + 1];
for (int i = 0;i < treenums;i++)
{
cin >> turns;
cin >> init;
ap[i].total = init;
ap[i].cutnum = new int[turns];
ap[i].dropapple = 0;
for (int j = 0;j < turns - 1;j++)
{
cin >> cutnums;
if (cutnums <= 0)
{
ap[i].cutnum[j] = cutnums;
totalcut += cutnums;
}
if (cutnums > 0)
{
if ((ap[i].total + totalcut) <= cutnums)
{
ap[i].total = cutnums;
totalcut = 0;
}
else
{
ap[i].dropapple = 1;
ap[i].total = cutnums;
totalcut = 0;
}
}
}
ap[i].total += totalcut;
totalnum += ap[i].total;
totalcut = 0;
}
int droptreenums = 0;
int continuedrop = 0;
for (int i = 0;i < treenums;i++)
{
if (ap[i].dropapple == 1)
{
droptreenums++;
}
if (ap[i].dropapple == 1 && ap[f(i + 1) % treenums].dropapple == 1 && ap[f(i + 2) % treenums].dropapple == 1)
{
continuedrop++;
}
}
cout << totalnum << " " << droptreenums << " " << continuedrop;
//有new一定要有正确的delete,否则会造成内存泄漏
for (int i = 1;i <= treenums;i++)
{
delete[]ap[i].cutnum;
}
delete[]ap;
return 0;
}