POJ 3895 Cycles of Lanes

题意是求最大环的边数。做这题发现用vector特别好用。DFS即可。
/*
ID: sdj22251
PROG: calfflac
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define MAX 100000000
#define LOCA
#define PI acos(-1.0)
using namespace std;
bool used[4455];
int num[4455];
int maxlen;
vector<int>G[4455];
void dfs(int v, int t)
{
    int i;
    num[v] = t;
    used[v] = true;
    int x = G[v].size();
    for(i = 0; i < x; i++)
    {
        if(!used[G[v][i]])
        {
            dfs(G[v][i], t + 1);
        }
        else
        {
            if(maxlen < num[v] - num[G[v][i]] + 1)
            maxlen = num[v] - num[G[v][i]] + 1;
        }
    }
}
int main()
{
#ifdef LOCAL
    freopen("ride.in","r",stdin);
    freopen("ride.out","w",stdout);
#endif
    int T, n, m, i, j, x, y;
    scanf("%d", &T);
    while(T--)
    {
        memset(used, false, sizeof(used));
        memset(num, 0, sizeof(num));
        scanf("%d%d", &n, &m);
        for(i = 1; i <= n; i++)
        G[i].clear();
        for(i = 0; i < m; i++)
        {
            scanf("%d%d", &x, &y);
            G[x].push_back(y);
            G[y].push_back(x);
        }
        maxlen = 0;
        for(i = 1; i <= n; i++)
        {
            if(!used[i])
            dfs(i, 1);
        }
        if(maxlen > 2) printf("%d\n", maxlen);
        else puts("0");
    }
    return 0;
}

你可能感兴趣的:(POJ 3895 Cycles of Lanes)