# BZOJ 1064: [Noi2008]假面舞会（dfs + 图论好题！）

http://www.lydsy.com/JudgeOnline/problem.php?id=1064

题意：

①无环并且是树：

②存在环并且顺序相同

③存在环并且顺序不同

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100000+5;

int n,m,tot,ans,mx,mi;
bool vis[maxn], flag[maxn];

struct node
{
int v,w,next;
}e[2000005];

void addEdge(int u, int v, int w)
{
e[tot].v = v;
e[tot].w = w;
}

int gcd(int a, int b)
{
return b==0?a:gcd(b,a%b);
}

void dfs1(int u)
{
vis[u] = 1;
{
int v = e[i].v;
if(!vis[v])
{
d[v] = d[u] + e[i].w;
dfs1(v);
}
else ans = gcd(ans, abs(d[u] + e[i].w - d[v]));
}
}

void dfs2(int u)
{
mx = max(mx, d[u]);
mi = min(mi, d[u]);
vis[u] = 1;
{
int v = e[i].v;
if(!flag[i])
{
flag[i] = flag[i^1] = 1;
d[v] = d[u] + e[i].w;
dfs2(v);
}
}
}

int main()
{
//freopen("in.txt","r",stdin);
scanf("%d%d",&n,&m);
tot = 0;
for(int i=0;i<m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
}
ans = 0;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
if(!vis[i])  dfs1(i);
}
if(ans)
{
int mi;
if(ans<3)  puts("-1 -1");
else
{
for(int i=3;i<=ans;i++)
{
if(ans%i == 0)  {mi = i; break;}
}
printf("%d %d\n",ans, mi);
}
}
else
{
memset(vis,0,sizeof(vis));
memset(flag,0,sizeof(flag));
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
mx = mi = d[i] = 0;
dfs2(i);
ans += mx-mi+1;
}
}
if(ans<3)  puts("-1 -1");
else printf("%d 3\n",ans);
}
return 0;
}


posted @ 2017-11-20 14:11  Kayden_Cheung  阅读(187)  评论(0编辑  收藏
//目录