1.题目描述:点击打开链接
2.解题思路:本题是贪心法的经典例题,贪心策略是:最短的和最长的匹配,次短的和次长的匹配,以此类推。如果不能匹配,则等待。注意要先排序。
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<string> #include<sstream> #include<set> #include<vector> #include<stack> #include<map> #include<queue> #include<deque> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<functional> using namespace std; #define maxn 100000+10 #define maxl 10000+10 int a[maxn]; int n, m; int main() { freopen("test.txt", "r", stdin); int T; scanf("%d", &T); while (T--) { memset(a, 0, sizeof(a)); char c=getchar(); while (c != '\n')c = getchar(); int cnt = 0; scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) scanf("%d", a + i); sort(a, a + n); int l = 0, r = n - 1,ml; while (l <= r)//逐个匹配 { ml = m - a[r--]; if (ml >= a[l])l++;//如果没找到匹配项,l不变,等待中 cnt++; } printf("%d\n", cnt); if (T)printf("\n"); } return 0; }