蓝桥杯 (C++ 求和 等差数列 顺子日期 灌溉)

目录

1、求和

题目: 

思路:

代码:

2、等差数列 

题目:

思路:

 代码:

3、顺子日期

题目: 

思路: 

代码:

4、灌溉

题目:

代码: 



1、求和

题目: 

a10994d10cf944fca4587200a03f3181.png

思路:

1、首先想到的是两重遍历,累加和。但是当n取200000时,会超时,所以暴力的遍历没有办法通过全部案例。

2、将公式变形得到S=a1*(a2+....+an)+a2*(a3+....+an)+.....+an.

3、所以先求所有项的累加和sum,从第一项开始每次将sum减去一项自身ai乘以自身ai,再将这些和相加得到结果。

代码:

#include<iostream>
using namespace std;
int main()
{
	int n,a[200010];
	cin >> n;
	long long sum = 0;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
		sum += a[i];
	}
	long long ans = 0;
	for (int i = 0; i < n; i++)
	{
		sum -= a[i];
		ans += a[i] * sum;
	}
	cout << ans;
}

2、等差数列 

题目:

b3af1879ea7f4b38bd1c176f42eda1b6.png

思路:

1、求等差数列,一开始想到直接找它们的最小差作为公差,但实际上是不行的,这可能没有办法构成等差数列。(比如:15、5、1这三个数,如果取5-1的差4为公差,会发现1、5、9、13、17,15不在等差数列中,所以不可取。)

2、通过上面的例子我们可以发现,我们要求的公差是可以满足一个数可以等于从另一个数加公差的倍数。所以我们要求的公差,是将所有数从小到大排序,所有相邻两数差的最大公约数。(比如:1、5、15,差有4、10,它们的最大公约数为2,所以公差为2,构成1、3、5、7、9、11、13、15的等差数列。)

3、最后得到公差,个数即位最大的数减去最小的数/公差+1;有一种情况比较特殊,当公差为0,即每个数都相等的时候,个数即为n。

 代码:

#include<iostream>
#include<algorithm>
using namespace std;
long long gcd(int a, int b)//辗转相除,求最大公约数
{
	if (b == 0)
		return a;
	else
		return gcd(b, a % b);
}
int main()
{
	int n;
	cin >> n;
	long long a[100010];
	for (int i = 0; i < n; i++)
		cin >> a[i];
	sort(a, a + n);
	long long d = a[1] - a[0];
	for (int i = 2; i < n; i++)
	{
		d = gcd(d, a[i] - a[i - 1]);
	}
	if (a[n - 1] == a[0])
		cout << n;
	else
		cout << ((a[n - 1] - a[0]) / d )+ 1;
}

3、顺子日期

题目: 

aac965a693504de3b78531c344c1c22b.png

思路: 

1、判断每一天是否存在顺子序列:012、123、234.......,只要存在一个顺子序列即为顺子日期。

代码:

#include<iostream>
#include<algorithm>
using namespace std;
int judge(int t[])
{
	int flag = 0;
	for (int i = 3; i <= 5; i++)
	{
		if (t[i] == (t[i + 1] - 1) && (t[i + 1] == t[i + 2] - 1))
		{
			flag = 1;
			break;
		}
	}
	return flag;
}
int main()
{
	int day[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	int t[8] = { 2,0,2,2 },ans = 0;
	for (int i = 1; i <= 12; i++)
	{
		t[4] = i / 10;
		t[5] = i % 10;
		for (int j = 1; j <= day[i]; j++)
		{
			t[6] = j / 10;
			t[7] = j % 10;
			if (judge(t))
			{
				ans++;
				//for (int i = 0; i < 8; i++)
					//cout << t[i];
				//cout << endl;
			}
		}
	}
	cout << ans;
}

4、灌溉

题目:

e79ac57a4b52496991e99d79a98a78ed.png

代码: 

#include<iostream>
#include<cmath>
using namespace std;
int n, m, t, r[110], c[110];
int main()
{
    cin >> n >> m >> t;
    for (int i = 1; i <= t; i++)
        cin >> r[i] >> c[i];
    int k;
    cin >> k;
    int cnt = 0;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            for (int l = 1; l <= t; l++)
            {
                int d = abs(r[l] - i) + abs(c[l] - j);
                if (d <= k)
                {
                    cnt++;
                    break;
                }
            }
        }
    }
    cout << cnt << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_74156152/article/details/134148714