[HDU 4324]Triangle LOVE[找环]

题目链接: [HDU 4324]Triangle LOVE[找环]

题意分析:

判断给出的图是否有一个长度为3的环。

解题思路:

dfs判断环,然后依据d数组判断深度是否符合。

个人感受:

嘛!网上有说A->B->C, A->C也算是三角恋,我觉得和题意不相符呀,并且依据这个推出了成n环即必有成三角环的结论。感觉还是直接判断长度为3的环靠谱,毕竟题目是说:“Triangle Love” means that among any three people (A,B and C) , A loves B, B loves C and C loves A. 

具体代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int INF = 0x7f7f7f7f, MAXN = 2e3 + 111;
vector<int> v[MAXN];
bool vis[MAXN];
int d[MAXN];

bool dfs(int u)
{
    vis[u] = 1;
    for (int i = 0; i < v[u].size(); ++i)
    {
        int cur = v[u][i];
        if (vis[cur] && d[u] == d[cur] + 2) return 1;
        if (vis[cur]) continue;
        d[cur] = d[u] + 1;
        if (dfs(cur)) return 1;
    }
    return 0;
}

int main()
{
    int n, t, kase = 0; scanf("%d", &t);
    while (t --)
    {
        scanf("%d", &n);
        getchar();
        char s[2015];
        for (int i = 0; i < n; ++i)
        {
            v[i].clear();
            gets(s);
            for (int j = 0; s[j]; ++j)
            {
                if (s[j] == '1')
                    v[i].push_back(j);
            }
        }
        bool flag = 0;
        memset(vis, 0, sizeof vis);
        for (int i = 0; i < n; ++i) //查找符合条件的三环
        {
            d[i] = 0;
            if (!vis[i] && dfs(i))
            {
                flag = 1;
                break;
            }
        }
        printf("Case #%d: ", ++kase);
        if (flag) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}




你可能感兴趣的:(HDU,DFS,判环)