loj 1009(dfs)

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=25835

思路:对每一个连通块将其染色,然后取颜色相同的最多的点,最后全部加起来即可。

PS:一开始没考虑到有可能有些点不出现,WA了好多次,然后改成将出现的点标记即可。

 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstring>

 4 #include<algorithm>

 5 #include<vector>

 6 using namespace std;

 7 #define MAXN 222222

 8 

 9 struct Edge{

10     int v,next;

11 }edge[MAXN<<1];

12 

13 int n,m,NE;

14 int head[MAXN];

15 

16 void Insert(int u,int v)

17 {

18     edge[NE].v=v;

19     edge[NE].next=head[u];

20     head[u]=NE++;

21 }

22 

23 int color[MAXN],block;

24 vector<vector<int> >g;

25 

26 void dfs(int u,int state)

27 {

28     color[u]=state;

29     g[block].push_back(u);

30     for(int i=head[u];i!=-1;i=edge[i].next){

31         int v=edge[i].v;

32         if(color[v]==0)dfs(v,3-state);

33     }

34 }

35 

36 

37 int main()

38 {

39     int _case,u,v,t=1;

40     scanf("%d",&_case);

41     while(_case--){

42         scanf("%d",&m);

43         n=0;

44         NE=0;

45         memset(head,-1,sizeof(head));

46         memset(color,-1,sizeof(color));

47         while(m--){

48             scanf("%d%d",&u,&v);

49             Insert(u,v);

50             Insert(v,u);

51             color[u]=color[v]=0;

52             n=max(n,max(u,v));

53         }

54         block=0;

55         g.clear();

56         g.resize(n+2);

57         for(int i=1;i<=n;i++){

58             if(color[i]==0){

59                 dfs(i,1);

60                 block++;

61             }

62         }

63         int ans=0,ans1=0,ans2=0;

64         for(int i=0;i<block;i++){

65             ans1=ans2=0;

66             for(int j=0;j<g[i].size();j++){

67                 if(color[g[i][j]]==1)ans1++;

68                 else if(color[g[i][j]]==2)ans2++;

69             }

70             ans+=max(ans1,ans2);

71         }

72         printf("Case %d: %d\n",t++,ans);

73     }

74 }
View Code

 

你可能感兴趣的:(DFS)