其他分享
首页 > 其他分享> > POJ - 2231 Moo Volume自己的菜鸡解法,参考一下吧

POJ - 2231 Moo Volume自己的菜鸡解法,参考一下吧

作者:互联网

正确代码如下,如果想看我以前 的错误代码可以无聊的往下翻;

#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace std;
long long a[10005];
int main()
{
	long long n;
	cin >> n;
	long long sum = 0,sum1 = 0;
	for (long long i = 0; i < n; ++i)
	{
		cin >> a[i];
	}
	sort(a,a + n);
	for (int i = n - 1; i > 0; 1)
	{
		int j;
		for (j = 0; j < n; ++j)
		{
			if((i == j && n % 2 == 1) || (i + 1 == j)&& n % 2 == 0) break;
			sum += (a[i] - a[j]) * (i - j) * 2;
			i--;
		}
		if((i == j && n % 2 == 1) || (i + 1 == j)&& n % 2 == 0) break;
	}
	cout << sum <<endl;
}

讲一下,这个用把数组开在int main外面,我怕出问题直接long long 了,原谅我是个蒟蒻,鉴于之前超时 的经验,我就简单的推导了一下,然后发现了可以用 总的sum == (a[i] -a[j] )* (i - j) * 2 , i–,j++;这么累加起来,而且复杂度比直接循环少了很多的 ,但是在判断何时终止循环时要分 n为奇数还是偶数,在if那里,然后自己看代码吧。

贪心题目,一开始直接循环然后TLE,,,,

#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace std;
long long a[10005];
int main()
{
	long long n;
	cin >> n;
	long long sum = 0,sum1 = 0;
	for (long long i = 0; i < n; ++i)
	{
		cin >> a[i];
	}
	for (long long i = 0; i < n; ++i)
	{
		for (long  j = 0; j < n; ++j)
		{
			if(a[i] - a[j] >= 0)
				sum += (a[i] - a[j]);
			else
				sum -= (a[i] - a[j]);
		}
	}
	cout << sum <<endl;
}

错了
于是稍微减少了循环的次数改进一下算法

#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace std;
long long a[10005];
int main()
{
	long long n;
	cin >> n;
	long long sum = 0,sum1 = 0;
	for (long long i = 0; i < n; ++i)
	{
		cin >> a[i];
	}
	sort(a,a + n);
	for (long long i = 0; i < n; ++i)
	{
		for (long long j = i; j < n; ++j)
		{
			if(a[i] - a[j] >= 0)
				sum += (a[i] - a[j]) * 2;
			else
				sum -= (a[i] - a[j]) * 2;
		}
	}
	cout << sum <<endl;
}

结果还是LTE,

fredvioce 发布了4 篇原创文章 · 获赞 0 · 访问量 79 私信 关注

标签:2231,sum,cin,long,Volume,++,int,Moo,include
来源: https://blog.csdn.net/fredvioce/article/details/104123557