• 图论6——仙人掌图


    如果某个无向连通图的任意一条边至多只出现在一条简单回路(simple cycle)里,我们就称这张图为仙人掌

    图(cactus)。所谓简单回路就是指在图上不重复经过任何一个顶点的回路。

      输入的第一行包括两个整数n和m(1≤n≤50000以及0≤m≤10000)。其中n代表顶点个数,我们约定图中的顶
    点将从1到n编号。接下来一共有m行。代表m条路径。每行的开始有一个整数k(2≤k≤1000),代表在这条路径上
    的顶点个数。接下来是k个1到n之间的整数,分别对应了一个顶点,相邻的顶点表示存在一条连接这两个顶点的边
    。一条路径上可能通过一个顶点好几次,比如对于第一个样例,第一条路径从3经过8,又从8返回到了3,但是我们
    保证所有的边都会出现在某条路径上,而且不会重复出现在两条路径上,或者在一条路径上出现两次。

      只需输出一个数,这个数表示仙人图的直径长度。

    输入 

    15 3
    9 1 2 3 4 5 6 7 8 3
    7 2 9 10 11 12 13 10
    5 2 14 9 15 10 8
    10 1
    10 1 2 3 4 5 6 7 8 9 10

    输出 

    8
    9

    程序来自Echo宝贝儿(博客园) 


    #include<iostream>
    #include<cstdio>
    #define INF 1e9
    #define maxn 50010
    using namespace std;
    int n,m,cnt,num,ans;
    int head[maxn],dep[maxn],f[maxn];
    int low[maxn],dfn[maxn],fa[maxn];
    int a[maxn],q[maxn],l,r;
    struct node{
        int to,pre;
    }e[20000010];
    void Insert(int from,int to){
        e[++num].to=to;
        e[num].pre=head[from];
        head[from]=num;
    }
    void dp(int root,int x){
        int tot=dep[x]-dep[root]+1;
        for(int i=x;i!=root;i=fa[i])a[tot--]=f[i];
        a[tot]=f[root];
        tot=dep[x]-dep[root]+1;
        for(int i=1;i<=tot;i++)a[i+tot]=a[i];
        q[1]=1;l=r=1;
        for(int i=2;i<=2*tot;i++){
            while(l<=r&&i-q[l]>tot/2)l++;
            ans=max(ans,a[i]+i+a[q[l]]-q[l]);
            while(l<=r&&a[q[r]]-q[r]<=a[i]-i)r--;
            q[++r]=i;
        }
        for(int i=2;i<=tot;i++)
            f[root]=max(f[root],a[i]+min(i-1,tot-i+1));
    }
    void dfs(int x){
        low[x]=dfn[x]=++cnt;
        for(int i=head[x];i;i=e[i].pre){
            int to=e[i].to;
            if(to!=fa[x]){
                if(!dfn[to]){
                    fa[to]=x;
                    dep[to]=dep[x]+1;
                    dfs(to);
                    low[x]=min(low[x],low[to]);
                }
                else low[x]=min(low[x],dfn[to]);
                if(dfn[x]<low[to]){
                    ans=max(ans,f[x]+f[to]+1);
                    f[x]=max(f[x],f[to]+1);
                }
            }
        }
        for(int i=head[x];i;i=e[i].pre){
            int to=e[i].to;
            if(fa[to]!=x&&dfn[x]<dfn[to])dp(x,to);
        }
    }
    int main(){
        freopen("Cola.txt","r",stdin);
        scanf("%d%d",&n,&m);
        int x,y,c;
        for(int i=1;i<=m;i++){
            scanf("%d%d",&c,&x);
            for(int i=2;i<=c;i++){
                scanf("%d",&y);
                Insert(x,y);Insert(y,x);
                x=y;
            }
        }
        dfs(1);
        printf("%d\n",ans);
        return 0;
    }
  • 相关阅读:
    shell面试题整理
    用循环链表实现Josephus问题
    in与exists的区别
    单链表的建立/测长/打印/删除/排序/逆序/寻找中间值
    float在内存中的存放
    crontab定时任务详解
    螺旋队列问题之二
    螺旋队列问题之一
    android网络编程--从网络下载图片,并保存到内存卡
    android Shader类简介_渲染图像示例
  • 原文地址:https://www.cnblogs.com/idyllic/p/10840987.html
Copyright © 2020-2023  润新知