洛谷试炼场刷题

珠心算:给定一列数,其中有几个数是另外两个数之和

 1、一开始想到的就是三重for循环:

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1001;
int a[maxn],n;
int main()
{
    cin>>n;
    for(int i = 1;i<=n;i++)
    {
        cin>>a[i];
    }
    int tot = 0;
    for(int k = 1;k<=n;k++)
        for(int i = 1;i<=n-1;i++)
            for(int j = i+1;j<=n;j++)
                if(a[k] == a[i] + a[j] && a[i] != a[j])
                
                    
                        tot++;
                       
                    
    cout<<tot<<endl;
    return 0;
}

满心欢喜,以为一下就用暴力找到了答案正解,于是发现,不能AC

通过比较输出结果:

发现原来存在这样的情况:如果一个数等于其他对数之和,那就有几对就算了几次,而本题是计算有多少个数是另外两个数之和,即只算一次就可以了。于是傻傻的不再理解正解答案中的什么k++,i = j = 1;

直接多用一个数组,如果找到了置为1,后面如果再找到就不增加了。

于是AC代码就呼之欲出了:

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1001;
int a[maxn],n;
int f[10001];
int main()
{
    cin>>n;
    for(int i = 1;i<=n;i++)
    {
        cin>>a[i];
        f[a[i]] = 0;
    }
    int tot = 0;
    for(int k = 1;k<=n;k++)
        for(int i = 1;i<=n-1;i++)
            for(int j = i+1;j<=n;j++)
                if(a[k] == a[i] + a[j] && a[i] != a[j])
                    if(!f[a[k]])
                    {
                        tot++;
                        f[a[k]] = 1;
                    }
    cout<<tot<<endl;
    return 0;
}

 ISBN:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctype.h>
using namespace std;
string s;
int main()
{
    cin>>s;
    int len = s.size(),sb,sum = 0,tot = 1;
    for(int i = 0;i<len-1;i++)
    {
        if(isdigit(s[i]))
        {
            sum += (s[i] - '0') * tot;
            tot++;
        }
    }
    sum %= 11;
    char c = (sum == 10 ? 'X' : (sum + '0'));
    if(c == s[len-1])
        cout<<"Right"<<endl;
    else{
        for(int i = 0;i<len-1;i++)
            cout<<s[i];
        cout<<c<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/longxue1991/p/12453599.html