codeforces 402B - Trees in a Row

题目链接:http://codeforces.com/problemset/problem/402/B

题目大意:给出这n棵树的高度,通过增加或是减少树的高度使得第i棵树比第i-1棵树高k米,求最小的步数及每步的操作。

题目分析1:枚举以哪棵树为基准。

代码参考1:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<string>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
const int N = 2000;
int a[N], b[N];

int main()
{
	int n, k, i, j;

	while (~scanf("%d%d", &n, &k))
	{
		memset(b, 0, sizeof(b));

		for (i = 0; i < n; ++i)
		{
			scanf("%d", &a[i]);
		}

		for (i = 0; i < n; ++i)//枚举基准
		{
			for (j = n - 1; j >= 0; --j)
			{
				int d = j - i;

				if (a[j] - a[i] != d * k)//如果他们的高度差不符合条件,改变次数+1
				{
					b[i]++;
				}
			}

			if (a[i] - i * k <= 0)//a[0]是最小的数,如果它<=0的话就不符合条件,赋值为INF
			{
				b[i] = N;
			}
		}

		int m = N, p;

		for (i = 0; i < n; ++i)//选出修改次数最小的数和所在位置
		{
			if (b[i] < m)
			{
				m = b[i];//最小次数
				p = i;//所在位置
			}
		}

		printf("%d\n", m);

		for (j = 0; j < n; ++j)//输出每步的具体操作
		{
			int d = a[j] - a[p] - (j - p - 1) * k;

			if (d > k)
			{
				printf("- %d %d\n", j + 1, d - k);
			}
			else
				if (d < k)
				{
					printf("+ %d %d\n", j + 1, k - d);
				}
		}

	}

	return 0;
}

====================================================================================================================================

代码参考2:(小土豆的~)

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<string>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
int cnt[1 << 10];
int arr[1 << 10];
int main()
{
	int n, k, i, a;

	while (~scanf("%d%d", &n, &k))
	{
		memset(cnt, 0, sizeof(cnt));

		for (i = 1; i <= n; ++i)
		{
			scanf("%d", &a);
			arr[i] = a;

			if (a - (i - 1)*k > 0)
			{
				++cnt[a - (i - 1)*k];//a-(i-1)*k以i为基准1位置该有的高度
				//5 1
				//1 1 1 2 3
				//能让首项为1的有2个,能让首项为2或3的都只有1个,所以首项就是1了
			}
		}

		int ans = 0, base = -1;

		for (i = 0; i < 1<<10; ++i)//找出能让首项为i的次数最多的
		{
			if (cnt[i] > ans)
			{
				ans = cnt[i];
				base = i;
			}
		}

		printf("%d\n", n - ans);

		for (i = 1; i <= n; ++i)
		{
			if (base != arr[i])
			{
				if (base < arr[i])
				{
					printf("-");
				}
				else
				{
					printf("+");
				}

				printf(" %d %d\n", i, abs(base - arr[i]));
			}

			base += k;
		}
	}

	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章