美团笔试编程题-9.11

题目描述:一个商家选择地址x[i],在该位置的价值为y[i]。问选择多个地址并且使得任意两个地址之差绝对值大于等于k。
输入:k,x,y
如:
2
1,3,2,5
4,5,1,1
输出:
1,3,5
10

一种较笨拙的思路是:
1.先对x从小到排序
2.两层循环寻找最大价值

#include 
#include 
#include 
#include 

using namespace std;


int main()
{
    int k;
    string x, y;
    vector<vector<int> > xy(100, vector<int>(2,0));
    while (cin >> k >> x >> y)
    {
        int lenx = x.size();
        int len = 0;
        for (int i=0; iif (i%2 == 0)
            {
                //cout << "x[i]:" << x[i] << endl;
                xy[len][0] = x[i]-'0';
                xy[len][1] = y[i]-'0';
                len++;

            }
        }
        //二维数组按第一列从小到大排序
        for (int i=0; ifor (int j=len-1; j>i; j--)
            {
                if (xy[j][0] < xy[j-1][0])
                {
                    int temp, temp1;
                    temp = xy[j][0];
                    xy[j][0] = xy[j-1][0];
                    xy[j-1][0] = temp;
                    temp1 = xy[j][1];
                    xy[j][1] = xy[j-1][1];
                    xy[j-1][1] = temp1;

                }
            }
        }

        int ans = 0, left = 0;
        for (int i=0; iint ans_temp = xy[i][1];
            int pos = i;
            for (int j=i+1; jif (xy[j][0] - xy[pos][0] >= k)
                {
                    ans_temp += xy[j][1];
                    pos = j;
                }
            }
            if (ans_temp > ans)
            {
                left = i;
            }
            ans = ans >= ans_temp ? ans:ans_temp;
        }
        cout << xy[left][0];
        int pos = left;
        for (int i=left+1; iif (xy[i][0] - xy[pos][0] >= k)
            {
                cout << "," << xy[i][0];
                pos = i;
            }
        }
        cout << endl;
        cout << ans << endl;

    }

    return 0;
}

你可能感兴趣的:(数据挖掘笔试面试题归纳总结)