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;
}



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