标签:
1 /*
2 题意:给一个树,节点上有权值,问最多能找出多少个点满足在树上是连通的并且按照权值排序后相邻的点
3 在树上的路径权值都小于这两个点
4 DFS/BFS+思维:按照权值的大小,从小的到大的连有向边,搜索最多连接点数即是答案。因为排序后,他们之间的路径,
5 可定都是从当前节点u连过去的,那么都是小于这两个节点的。DFS需手动加栈,BFS类似拓扑排序的思路
6 */
7 #pragma comment (linker, "/STACK:1024000000,1024000000")
8 #include <cstdio>
9 #include <cstring>
10 #include <algorithm>
11 #include <vector>
12 using namespace std;
13
14 const int MAXN = 5e5 + 10;
15 const int INF = 0x3f3f3f3f;
16 int w[MAXN];
17 int cnt[MAXN];
18 vector<int> G[MAXN];
19 int n;
20
21 void DFS(int u) {
22 cnt[u] = 1;
23 for (int i=0; i<G[u].size (); ++i) {
24 int v = G[u][i];
25 if (!cnt[v]) DFS (v);
26 cnt[u] += cnt[v];
27 }
28 }
29
30 int main(void) { //HDOJ 5325 Crazy Bobo
31 //freopen ("J.in", "r", stdin);
32
33 while (scanf ("%d", &n) == 1) {
34 for (int i=1; i<=n; ++i) scanf ("%d", &w[i]);
35 for (int i=1; i<=n; ++i) G[i].clear ();
36 for (int i=1; i<=n-1; ++i) {
37 int u, v; scanf ("%d%d", &u, &v);
38 if (w[u] < w[v]) G[u].push_back (v);
39 else G[v].push_back (u);
40 }
41 memset (cnt, 0, sizeof (cnt));
42 for (int i=1; i<=n; ++i) {
43 if (cnt[i]) continue;
44 DFS (i);
45 }
46 int ans = 0;
47 for (int i=1; i<=n; ++i) ans = max (ans, cnt[i]);
48 printf ("%d\n", ans);
49 }
50
51 return 0;
52 }
1 #include <cstdio>
2 #include <cstring>
3 #include <algorithm>
4 #include <vector>
5 #include <queue>
6 using namespace std;
7
8 const int MAXN = 5e5 + 10;
9 const int INF = 0x3f3f3f3f;
10 int w[MAXN];
11 int cnt[MAXN];
12 int deg[MAXN];
13 vector<int> G[MAXN];
14 int n;
15
16 int BFS(void) {
17 queue<int> Q; int ret = 0;
18 for (int i=1; i<=n; ++i) cnt[i] = 1;
19 for (int i=1; i<=n; ++i) {
20 if (!deg[i]) Q.push (i);
21 }
22 while (!Q.empty ()) {
23 int u = Q.front (); Q.pop ();
24 ret = max (ret, cnt[u]);
25 for (int i=0; i<G[u].size (); ++i) {
26 int v = G[u][i];
27 cnt[v] += cnt[u];
28 if (!(--deg[v])) Q.push (v);
29 }
30 }
31 return ret;
32 }
33
34 int main(void) {
35 //freopen ("J.in", "r", stdin);
36
37 while (scanf ("%d", &n) == 1) {
38 for (int i=1; i<=n; ++i) scanf ("%d", &w[i]);
39 for (int i=1; i<=n; ++i) G[i].clear ();
40 memset (deg, 0, sizeof (deg));
41 for (int i=1; i<=n-1; ++i) {
42 int u, v; scanf ("%d%d", &u, &v);
43 if (w[u] < w[v]) swap (u, v);
44 G[u].push_back (v); deg[v]++;
45 }
46 printf ("%d\n", BFS ());
47 }
48
49 return 0;
50 }
DFS/BFS+思维 HDOJ 5325 Crazy Bobo
标签:
原文地址:http://www.cnblogs.com/Running-Time/p/4685195.html