一般仙人掌问题,都要分情况,树上一种处理方式,环上另一种处理方式。
/**************************************************************Problem: 1023User: zhhxLanguage: C++Result: AcceptedTime:744 msMemory:13204 kb
****************************************************************/#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<vector>
#include<utility>
#define fi first
#define se second
#define MK(a,b) make_pair((a),(b))
#define pii pair<int,int>
using namespace std;
const int N=100005;int n,m;vector<int> E1[N],E2[N],disE[N];
void add(int u,int v) {E1[u].push_back(v);}
void addedge(int u,int v,int d){E2[u].push_back(v);disE[u].push_back(d);}int dfn[N],cnt,fa[N],dis[N],from[N],len[N],num;
bool b[N];void dfs1(int u)
{dfn[u]=++cnt;int v,sz=E1[u].size();for (int i=0;i<sz;i++)if ((v=E1[u][i])!=fa[u]){if (dfn[v]==0){dis[v]=dis[u]+1;fa[v]=u;dfs1(v);}else if (dfn[v]<dfn[u]){int tmp=u; n++;b[n]=true;addedge(v,n,0);num++;from[n]=num;len[num]=dis[u]-dis[v]+1;while (tmp!=v){addedge(n,tmp,min(dis[tmp]-dis[v],len[num]-(dis[tmp]-dis[v])));from[tmp]=num;tmp=fa[tmp];}}}if (from[u]==0) addedge(fa[u],u,1);
}pii f[N];
int ans;void MAX(pii &a,int tmp)
{if (tmp>a.fi) a.se=a.fi,a.fi=tmp;else if (tmp>a.se) a.se=tmp;
}
int q[N],head,tail,disq[N];void dfs2(int u)
{int sz=E2[u].size(),v;for (int i=0;i<sz;i++) {dfs2(v=E2[u][i]);MAX(f[u],f[v].fi+disE[u][i]);}if (!b[u])ans=max(ans,f[u].fi+f[u].se);else{int tail=0,head=1,anc=from[u],mx=-1e9;for (int i=sz-1;i>=0;i--){v=E2[u][i];while (head<=tail&&dis[v]-dis[q[head]]>len[anc]/2) {mx=max(mx,f[q[head]].fi+len[anc]+dis[q[head]]);head++;}ans=max(ans,mx+f[v].fi-dis[v]);if (head<=tail) ans=max(ans,disq[head]+dis[v]+f[v].fi);while (head<=tail&&disq[tail]<f[v].fi-dis[v]) tail--;q[++tail]=v;disq[tail]=f[v].fi-dis[v];}}
}int main()
{scanf("%d%d",&n,&m);int u,v,k;for (int i=1;i<=m;i++){scanf("%d",&k);scanf("%d",&u);for (int i=1;i<k;i++){scanf("%d",&v);add(u,v);add(v,u);u=v;}}dis[1]=1;dfs1(1);dfs2(1);printf("%d",ans);return 0;
}