Milk Factory【有向图】Rating

题目描述:

Milk Factory【有向图】Rating_第1张图片

思路:

通过add操作将两结点连通,然后进行深搜,当深度等于结点个数时即为答案。也可以用Floyd算法将结点连起来。

#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef unsigned long long ll;
const int mod=1e6+7;


const int N = 10100;

int gh[N], gn[N], gv[N], len;

void add(int b, int a)
{
    gv[len] = a;
    gn[len] = gh[b];
    gh[b] = len++;
}

bool vis[200];

int dfs(int x)
{
    int cur = 1;
    vis[x] = true;
    for (int i = gh[x]; i != -1; i = gn[i])
    {
        int k = gv[i];
        if (!vis[k])
            cur += dfs(k);
        else
            break;
    }
    return cur;
}

int main()
{
    int n;
    cin>>n;
    memset(gh, -1, sizeof(gh));
    memset(gn, -1, sizeof(gn));
    for (int i = 1; i < n; i++)
    {
        int a, b;
        cin>>a>>b;
        add(b, a);
    }
    int res = -1;
    for (int i = 1; i <= n; i++)
    {
        memset(vis, 0, sizeof(vis));
        if (dfs(i) == n)
        {
            res = i;
            break;
        }
    }
    cout<<res<<endl;
    return 0;
}

你可能感兴趣的:(算法题解)