POJ_1456 Supermarket 【并查集/贪心】

一、题面

POJ1456

二、分析

1.贪心策略:先保证从利润最大的开始判断,然后开一个标记时间是否能访问的数组,时间尽量从最大的时间开始选择,这样能够保证后面时间小的还能够卖。

2.并查集:并查集直接加快了判断该时间能否卖的速度,贪心原理相同。

三、AC代码

 1 //贪心
 2 #include <cstdio>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <queue>
 6 #include <algorithm>
 7 #include <fstream>
 8 
 9 using namespace std;
10 
11 const int MAXN = 1e4+2;
12 struct Node
13 {
14     int px, dx;
15     bool operator<(const Node t)const
16     {
17         return px > t.px;
18     }
19 }Data[MAXN];
20 bool flag[MAXN];
21 
22 
23 int main()
24 {
25     //freopen("input.txt", "r", stdin);
26     int N, Ans;
27     while(scanf("%d", &N)!=EOF)
28     {
29         Ans = 0;
30         for(int i = 0; i < N; i++)
31             scanf("%d %d", &Data[i].px, &Data[i].dx);
32         sort(Data, Data+N);
33         memset(flag, 0, sizeof(flag));
34         for(int i = 0; i < N; i++)
35         {
36             for(int j = Data[i].dx; j >= 1; j--)
37             {
38                 if(!flag[j])
39                 {
40                     Ans += Data[i].px;
41                     flag[j] = 1;
42                     break;
43                 }
44             }
45         }
46         printf("%d\n", Ans);
47     }
48     return 0;
49 }
贪心
 1 //并查集加速
 2 #include <cstdio>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <queue>
 6 #include <algorithm>
 7 #include <fstream>
 8 
 9 using namespace std;
10 
11 const int MAXN = 1e4+2;
12 struct Node
13 {
14     int px, dx;
15     bool operator<(const Node t)const
16     {
17         return px > t.px;
18     }
19 }Data[MAXN];
20 bool flag[MAXN];
21 int par[MAXN];
22 
23 int Find(int x)
24 {
25     if(par[x] == -1) 
26         return x;
27     return par[x] = Find(par[x]);
28 }
29 
30 
31 int main()
32 {
33     //freopen("input.txt", "r", stdin);
34     int N, Ans;
35     while(scanf("%d", &N)!=EOF)
36     {
37         Ans = 0;
38         for(int i = 0; i < N; i++)
39             scanf("%d %d", &Data[i].px, &Data[i].dx);
40         sort(Data, Data+N);
41         memset(flag, 0, sizeof(flag));
42         memset(par, -1, sizeof(par));
43         for(int i = 0; i < N; i++)
44         {
45             int f = Find(Data[i].dx);   //判断该时间以下是否有时间可以卖
46             if(f > 0)
47             {
48                 Ans += Data[i].px;
49                 par[f] = f-1;
50             }
51         }
52         printf("%d\n", Ans);
53     }
54     return 0;
55 }
并查集

猜你喜欢

转载自www.cnblogs.com/dybala21/p/10140594.html