刷题笔记-数学

买不到的数目

思路:

这类问题,没有什么思路时,可以采用打表找规律的方法:

#include <iostream>
using namespace std;

bool dfs(int i , int n , int m)
{
    if(i == 0)   return true;
    if(i < n)    return false;
    if(dfs(i - n , n , m))
        return true;
    if(dfs(i - m , n , m))
        return true;
    
    return false;
}
int main(void)
{
    int n,m;
    cin >> n >> m;
    for(int i = 1000; i > 0; i --)
        if(!dfs(i , n , m))
        {
            cout << i << endl;
            break;
        }
    
    return 0;
}

结果: 2 3 1
2 5 3 3 5 7 4 5 11 2 7 5 3 7 11 4 7 17 规律是:(n - 1)(m - 1) - 1

代码:

#include <iostream>
using namespace std;

int main(void)
{
    int n,m;
    cin >> n >> m;
    cout << (n-1)*(m-1)-1 << endl;
    
    return 0;
}

蚂蚁感冒

思路:

最关键的一点:两个蚂蚁掉头,是可以和两个蚂蚁相互穿过等价的 在能想到上面这一点后,分析就简单了。只需要分别统计第一个感冒蚂蚁右边向左的蚂蚁、左边向右的蚂蚁总数即可。

###代码:

#include <iostream>
using namespace std;

int main(void)
{
    int n;
    cin >> n;
    int a[55];
    for(int i = 0; i < n;i++)
        cin >> a[i];
    
    int l = 0,r = 0;
    for(int i = 1; i < n;i++)
    {
        if(abs(a[i]) > abs(a[0]) && a[i] < 0) l++;
        if(abs(a[i]) < abs(a[0]) && a[i] > 0) r++;
    }
    //特殊情况:例如感冒蚂蚁向右,如果右边向左的蚂蚁数为0,则不会有其他蚂蚁被传染
    if(a[0] > 0 && l == 0 || a[0] < 0 && r == 0)
        cout << 1 << endl;
    else
        cout << l + r + 1 << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zy200128/p/12673944.html