【hihoCoder】1121:二分图一·二分图判定

  题目   http://hihocoder.com/problemset/problem/1121

无向图上有N个点,两两之间可以有连线,共有M条连线

如果对所有点进行涂色(白/黑),判定是否存在一个合理的涂色方案,使得图上每一条连线两端的顶点颜色都不相同

  思路  

1. 深度优先搜索把图上所有的点都遍历一遍 

  代码注意点   

1. 因为不想用二维数组,采用vector<vector<int>>的类型。这时要注意初始化方式:

不该用的方式

//1. 初始化
vector<int> tmp(N); 
vector<vector<int>> data(N, tmp);
//2. 访问方式
cin>>data[i][j]

合适的方式

//1. 初始化
vector<vector<int>> data;
data.resize(N);
//2. 访问方式
int x, y;
cin>>x>>y;
data[x].push_back(y);
data[y].push_back(x);

2. vector的resize/reserve函数

1) void reserve (size_type n);

  • 预分配存储区大小,即capacity,但是没有对内存初始化,不能有效地访问
  • 实际分配的大小可能大于n,即capacity >= n

2) void resize (size_type n, value_type val = 0);

  • 重新分配大小,vector中现有的元素个数 size()
  • n <= 原始大小,则减少size()值,保存前n个元素
  • n >= 原始大小,则插入元素(默认为0, 或设置的 val),使size()达到n
  • n > capacity(),则重新分配存储空间 

 源码  

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 bool setPeople(vector<vector<int>>& date, vector<int>& people, int index)
 6 {
 7     int num = date[index].size();
 8     for (int i = 0; i < num; i++)
 9     {
10         int j = date[index][i];
11         if (people[j] == 0)//还没有设置过
12         {
13             people[j] = -people[index];
14             if (!setPeople(date, people, j))
15                 return false;
16         }
17         else  if (people[j] == people[index])//已经设置过, 不符合要求
18             return false;
19     }
20     return true;
21 }
22 int main()
23 {
24     int T, N, M, i;//N个人,M对
25     cin >> T;
26     vector<int> people;//0: 没有设置,1:红色 2:黑色
27     vector<vector<int>> date;
28     while (T-- > 0)
29     {
30         cin >> N >> M;
31         people.clear();
32         date.clear();
33         people.resize(N + 1, 0);
34         date.resize(N + 1);
35         
36         for (i = 0; i < M; i++)
37         {
38             int a, b;
39             cin >> a >> b;
40             date[a].push_back(b);
41             date[b].push_back(a);
42         }
43         for (i = 1; i <= N; i++)
44         {            
45             if (people[i] == 0)//没有设置过
46             {
47                 people[i] = -1;
48                 if (!setPeople(date, people, i))//有出现错误
49                     break;
50             }
51         }
52         if (i != N + 1)
53             cout << "Wrong" << endl;
54         else
55             cout << "Correct" << endl;
56     }
57     return 0;
58 }
View Code
原文地址:https://www.cnblogs.com/coolqiyu/p/5904177.html