牛客网程序题

腾讯2018春招技术类编程题

第一题

 1 #include<iostream>
 2 using namespace std;
 3 
 4 long Sum_arr(long n,long m)
 5 {
 6     long Sum=0;
 7     for(long i=1;i<=m;i++)
 8     {
 9         long flag=-1;
10         for(long j=i;j<=n;j+=m)
11         {
12             Sum+=j*flag;
13             flag=-flag;
14         }
15     }
16     return Sum;
17 }
18 
19 int main()
20 {
21     long n,m;
22     cin>>n>>m;
23     while(!(n>=2&&n<=(1e9)&&m>=1&&(n%(2*m))==0))
24         cin>>n>>m;
25     cout<<Sum_arr(n,m)<<endl;
26     return 0;
27 }

 第二题(有误)

#include<iostream>
#include<vector>
using namespace std;

void sort(vector<long> &aa, long p)
{
    for (long i = 0; i<p; i++)
    {
        long k=i;
        for (long j = i; j<p; j++)
        {
            if (aa[i]<aa[j])
                k=j;
        }
        swap(aa[i], aa[k]);
    }
}

long Fun(vector<long> arr, long n)
{
    sort(arr, n);
    long sum1 = 0, sum2 = 0;//sum1 牛牛
    for (long i = 0; i<n; i += 2)
        sum1 += arr[i];
    for (long i = 1; i<n; i += 2)
        sum2 += arr[i];
    return sum1 - sum2;
}

int main()
{
    long n;
    cin >> n;
    vector<long> arr(n);
    for (long i = 0; i<n; i++)
        cin >> arr[i];
    cout << Fun(arr, n)<< endl;
    return 0;
}

 

posted @ 2018-12-18 21:17  jackii  阅读(107)  评论(0编辑  收藏  举报