商汤科技2018.9.7----软件开发笔试第三题

//除不变的A,B外加一个next数组,再加一个保存以i+1为起始点,一直走下去所得的分数
//,修改next数组,如果不再增加点,遍历结束,退出
#include
#include
#include
#include
#include
#include
#include
using namespace std;


int main()
{
    int N;
    while (cin >> N)
    {
        vector<int> A, B;
        int mark_a, mark_b;
        for (int i = 0; i < N; ++i)
        {
            cin >> mark_a >> mark_b;
            A.push_back(mark_a);
            B.push_back(mark_b);
        }
        int max_index = 0;
        for (int i = 0; i < N; ++i)
        {
            if (A[i] > A[max_index])max_index = i;
        }
        int max_value = A[max_index];

        vector<set<int>> the_set(N);
        vector<int> next = B;
        vector<int> save_A = A;
        while (1)
        {
            bool flag = true;
            for (int i = 0; i < N; ++i)
            {
                if (find(the_set[i].begin(), the_set[i].end(), next[i])==the_set[i].end())
                {
                    flag = false;
                    save_A[i] += A[next[i]-1];
                    if (save_A[i] > max_value)
                    {
                        max_value = save_A[i];
                    }
                    the_set[i].insert(next[i]);
                }
                next[i] = B[next[i]-1];
            }
            if (flag == true)
            {
                break;
            }
        }
        cout << max_value << endl;

    }
    return 0;
}

你可能感兴趣的:(笔试题)