这类问题没有固定的模板,但是也有一定的套路可循,一般都要用到“排序”这类的想法,比如sort或者priority_queue
int main()
{
int i,n, maxw,ans=0,wei[maxn],l,r;
scanf("%d%d", &n, &maxw);
for (i = 0; i < n; i++)
{
scanf("%d", &wei[i]);
}
sort(wei, wei + n);
l = 0;
r = n - 1;
while (l <= r)
{
if (wei[r] + wei[l] > maxw)
{
ans++;
r--;
}
else
{
ans++;
l++;
r--;
}
}
printf("%d\n", ans);
}
bool cmp(string a, string b)
{
return a + b > b + a;
}
int main()
{
int i,j,n;
string s[21];
scanf("%d", &n);
for (i = 0; i < n; i++)
{
cin >> s[i];
}
sort(s, s + n, cmp);
for (i = 0; i < n; i++)
{
cout << s[i];
}
}
struct node
{
int l;
int r;
friend bool operator <(const node l, const node r)
{
return l.r < r.r;
}
}a[1005];
int main()
{
int n, i, l, r, ans = 1;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> l >> r;
a[i] = { l,r };
}
sort(a, a + n);
int last = a[0].r;
for (i = 1; i < n; i++)
{
if (a[i].l >= last)
{
last = a[i].r;
ans++;
}
}
printf("%d\n", ans);
}
map<int,int>mp; //排序转化为数字大小
int n, t;
int main()
{
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
for (int i = 1, x; i <= n; i++)
{
scanf("%d", &x);
mp[log2(x)]++; //最高位是1、0对应的log2值相差1
}
long long ans = 0;
for (auto i : mp)
ans += (long long)i.second * (i.second - 1) / 2; //Cn取2
printf("%lld\n", ans);
mp.clear();
}
}
int main()
{
priority_queue<int, vector<int>, greater<int>>que;
long long sum = 0;
int i,n;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
int temp;
scanf("%d", &temp);
que.push(temp);
}
while (que.size()>1)
{
int temp1,temp2,temp;
temp1 = que.top();
que.pop();
temp2 = que.top();
que.pop();
temp = temp1 + temp2;
sum += temp;
que.push(temp);
}
printf("%lld\n", sum);
}
struct node
{
int l;
int r;
int list;
friend bool operator<(const node& a, const node& b)
{
return a.r > b.r;
}
}a[maxn];
bool cmp(node a, node b)
{
return a.l < b.l;
}
priority_queue<node>que;
int main()
{
int n, i, ans = 0, maxx;
int rank[maxn] = { 0 };
cin >> n;
for (i = 0; i < n; i++)
{
scanf("%d%d", &a[i].l, &a[i].r);
a[i].list = i;
}
sort(a, a + n, cmp);
//l最小的在“队”首(后面的元素就没办法从前面插入)
que.push(a[0]);
rank[a[0].list] = 1;
for (i = 1; i < n; i++)
{
if (que.top().r < a[i].l) //r最小在队首(最大程度利用)
{
rank[a[i].list] = rank[que.top().list]; //按原来次序记录所在位置
que.pop();
que.push(a[i]);
}
else
{
que.push(a[i]);
rank[a[i].list] = que.size();
}
}
maxx = que.size();
printf("%d\n", maxx);
for (i = 0; i < n; i++)
{
printf("%d\n", rank[i]); //i是原顺序,rank[i]是所在位置
}
}