POJ_1456 Supermarket 【並查集/貪心】
阿新 • • 發佈:2018-12-18
一、題面
二、分析
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 intN, 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 }並查集