笔试题

重要的城市

笔试题_第1张图片

笔试题_第2张图片
#include 
#include 
#include 

using namespace std;


int dfs(vector>& cities, int k, vector& temp)
{
    int count = 0;
    stack stack;
    vector visited(cities.size(), false);

    stack.push(k);
    while (!stack.empty())
    {
        int curNode = stack.top();
        if (visited[curNode])
        {
            stack.pop();
        }
        else
        {
            visited[curNode] = true;
            for (int i = 0; i < cities[curNode].size(); i++)
            {
                int v = cities[curNode][i];
                if (!visited[v])
                    stack.push(v);
            }
        }
    }

    for (int i = 1; i< cities.size(); i++)
    {
        if (visited[i])
        {
            temp[i] = temp[i] + 1;//如果城市k能访问到城市i,则城市i的进入路线城市加1
            ++count;//记录能进入城市i的所有城市总和
        }
    }
    return count;
}

int main()
{
    int vertexNum = 0;
    int edgesNum = 0;

    cin >> vertexNum >> edgesNum;
    vector> cities(vertexNum + 1, vector());
    for (int i = 0; i < edgesNum; i++)
    {
        int u, v;
        cin >> u >> v;
        cities[u].push_back(v);
    }

    vector s_in(vertexNum + 1, 0);//记录能进入每个城市的总数量
    vector s_out(vertexNum + 1, 0);//记录每个城市到达其他城市的总数量
    for (int i = 1; i <= vertexNum; i++)
    {
        s_out[i] = dfs(cities, i, s_in);
    }

    int importCityNum = 0;
    for (int i = 1; i <= vertexNum; i++)
    {
        if (s_in[i] > s_out[i])
            importCityNum++;
    }
    cout << importCityNum << endl;
}

题目:在抖音上,共有N个用户,如果A关注B,如果B关注C,则A间接关注了C,如果N个用户都关注了用户h(可以是直接关注和间接关注),则用户h为网红,求一共有多少网红?

输入:
第一行输入用户的数量N,和关系数量M
第二行输入M个关注关系

例如:
4 3
1 2 3 4 1 4

#include 
#include 
#include 

using namespace std;


void dfs(vector>& graph, int k, vector& res)
{
    stack stk;
    vector is_visited(graph.size(), false);

    stk.push(k);
    while (!stk.empty())
    {
        int node = stk.top();
        if (is_visited[node])
        {
            stk.pop();
        }
        else
        {
            is_visited[node] = true;
            for (int i = 0; i < graph[node].size(); i++)
            {
                int v = graph[node][i];
                if (!is_visited[v])
                    stk.push(v); 
            }
        }
    }

    for (int i = 1; i < graph.size(); i++)
    {
        if (is_visited[i])
            res[k] = res[k] + 1;
    }
}

int main() {
    int vertex_num = 0;
    int edges_num = 0;

    cin >> vertex_num >> edges_num;
    vector> graph(vertex_num + 1, vector());
    for (int i = 0; i < edges_num; i++)
    {
        int u, v;
        cin >> u >> v;
        graph[u].push_back(v);
    }

    vector res(vertex_num + 1, 0);
    for (int i = 1; i <= vertex_num; i++)
    {
        dfs(graph, i, res);
    }

    int count = 0;
    for (int i = 1; i <= vertex_num; i++)
    {
        if (res[i] == vertex_num)
            ++count;
    }
    cout << count << endl;
}

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