带花树算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#include<bits/stdc++.h>

#define N 1000007

using namespace std;

inline int read()

{

int x=0,f=1;char ch=getchar();

while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}

while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}

return x*f;

}

queue<int>Q;

int n,m,head[N],pos;

int tot,match[N],fri[N],top[N],ring[N];

bool odd[N],vis[N];

struct edge{int to,next;}e[N<<1];

inline void add(int a,int b)

{

pos++;e[pos].to=b,e[pos].next=head[a],head[a]=pos;

}

inline void insert(int u,int v){add(u,v);add(v,u);}

int fa[N];

inline int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}

int clo;

inline int lca(int x,int y)

{

clo++;

for(;x;x=find(top[x]))ring[x]=clo;

for(x=y;ring[x]!=clo;x=find(top[x]));

return x;

}

inline void blossom(int x,int y,int p)

{

for(;find(x)!=find(p);x=fri[y])

{

fri[x]=y,y=match[x];

fa[find(x)]=fa[find(y)]=p;

Q.push(y),odd[y]=0;

}

}

inline bool dfs(int s)

{

clo=0;

for(int i=1;i<=n;i++)odd[i]=vis[i]=ring[i]=top[i]=fri[i]=0,fa[i]=i;

while(!Q.empty())Q.pop();vis[s]=1,Q.push(s);

while(!Q.empty())

{

int u=Q.front();Q.pop();

for(int i=head[u];i;i=e[i].next)

{

int v=e[i].to;

if(!vis[v])

{

vis[v]=odd[v]=1,fri[v]=top[v]=u;

if(!match[v])

{

for(int x,y,j=v;j;j=y)

{

x=fri[j],y=match[x];

match[j]=x,match[x]=j;

}return 1;

}

vis[match[v]]=1,top[match[v]]=v,Q.push(match[v]);

}

else if(!odd[v]&&find(v)!=find(u))

{

int p=lca(u,v);

blossom(u,v,p);

blossom(v,u,p);

}

}

}return 0;

}

int main()

{

n=read();
m=read();

for(int i=1;i<=m;i++)
{
int x=read();
int y=read();

insert(x,y);

}

int ans=0;

for(int i=1;i<=n;i++)if(!match[i])ans+=dfs(i);

printf("%d\n",n-ans*2);

//for(int i=1;i<=n;i++)printf("%d ",match[i]);

}