Leetcode-5056 Flower Planting With No Adjacent(不邻接植花)

 1 #define _for(i,a,b) for(int i = (a);i < b;i ++)
 2 
 3 int n,m;
 4 
 5 class Solution
 6 {
 7     public:
 8         int color[10000];
 9         vector<vector<int>> a;
10         bool OK(int t)
11         {
12             for(int j=0; j<a[t].size(); j++)
13             {
14             //    if(a[t][j])
15             //    {
16                 if(color[t]==color[a[t][j]])
17                         return false;
18             //    }
19             }
20             return true;
21         }
22         bool traceback(int t)
23         {
24             int oldvalue=0;
25             if(t==n)
26             {
27                 return true;
28             }
29             for(int i=1; i<=m; i++) 
30             {
31                 oldvalue=color[t];
32                 color[t]=i;
33                 if(OK(t))
34                 {
35                     if(traceback(t+1)) return true;
36                 }
37                 color[t]=oldvalue;
38             }
39             return false;
40         }
41         vector<int> gardenNoAdj(int N, vector<vector<int>>& paths)
42         {
43             a.resize(10000);
44             n = N;
45             m = 4;
46             _for(i,0,paths.size())
47             {a[paths[i][0]-1].push_back(paths[i][1]-1);a[paths[i][1]-1].push_back(paths[i][0]-1);}
48             
49             traceback(0);
50             vector<int> rnt(N,0);
51             _for(i,0,N)
52                 rnt[i] = color[i];
53             return rnt;
54         }
55 };

染色问题,没想太多,搜就完事了

上一篇:负载均衡算法(待续)


下一篇:【思维+DP】UVA10635 Prince and Princess