poj3895Cycles of Lanes(dfs)

本文探讨了在给定的无向图中找到最大环的问题,通过实例输入和输出展示了解决策略,深入解析了解题过程和关键步骤。

Cycles of Lanes
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 930 Accepted: 347

Description

Each of the M lanes of the Park of Polytechnic University of Bucharest connects two of the N crossroads of the park (labeled from 1 to N). There is no pair of crossroads connected by more than one lane and it is possible to pass from each crossroad to each other crossroad by a path composed of one or more lanes. A cycle of lanes is simple when passes through each of its crossroads exactly once. 
The administration of the University would like to put on the lanes pictures of the winners of Regional Collegiate Programming Contest in such way that the pictures of winners from the same university to be on the lanes of a same simple cycle. That is why the administration would like to assign the longest simple cycles of lanes to most successful universities. The problem is to find the longest cycles? Fortunately, it happens that each lane of the park is participating in no more than one simple cycle (see the Figure). 

Input

On the first line of the input file the number T of the test cases will be given. Each test case starts with a line with the positive integers N and M, separated by interval (4 <= N <= 4444). Each of the next M lines of the test case contains the labels of one of the pairs of crossroads connected by a lane.

Output

For each of the test cases, on a single line of the output, print the length of a maximal simple cycle.

Sample Input

1 
7 8 
3 4 
1 4 
1 3 
7 1 
2 7 
7 5 
5 6 
6 2

Sample Output

4

Source


无向图中找一个最大环。。。

水货不解释。。。

#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 4500;
struct edge
{
    int to,next;
}lcm[N<<6];
int flag[N];
int head[N];
int n,m,num;
int ans;

void build(int u,int v)
{
    lcm[num].to = v;
    lcm[num].next = head[u];
    head[u] = num;
    num ++;
}

void dfs(int cur,int dp)
{
    int i;
    if(flag[cur])
    {
        if(ans < dp - flag[cur])
            ans = dp - flag[cur];
        //flag[cur] = dp;
        return;
    }
    flag[cur] = dp;
    for(i = head[cur];i != -1;i = lcm[i].next)
    {
        dfs(lcm[i].to,dp + 1);
    }
}

int main()
{
    int i,t;
    int a,b;
    scanf("%d",&t);
    while(t --)
    {
        num = 0;
        memset(head,-1,sizeof(head));
        memset(flag,0,sizeof(flag));
        scanf("%d%d",&n,&m);
        while(m --)
        {
            scanf("%d%d",&a,&b);
            build(a,b);
            build(b,a);
        }
        ans = 0;
        dfs(1,1);
        if(ans < 3)
            ans = 0;
        printf("%d\n",ans);
    }
    return 0;
}
//276K	16MS



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值