链接:https://www.nowcoder.com/acm/contest/112/A
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
现有n组人,m个地点,给出每组人的人数,每个地点可容纳的最大人数和选择的价格
要求一种方式,使得每组人都到一个各不相同的地点,最小化选择的价格
每个队伍的人都要在同一个地方每个地方只能有一个队伍
输入描述:
第一行n,m 第二行n个数,表示每组的人数 接下来m行,每行两个数,表示可容纳的最大人数和选择的价格
输出描述:
输出最小化选择的价格,无解输出-1
示例1
输入
3 4 2 3 4 1 2 2 3 3 4 4 5
输出
12
备注:
所有数据小于1e5
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<stdlib.h>
#include<queue>
#include<algorithm>
using namespace std;
const int N=1e5+1;
int s[N];
bool vis[N];
struct node
{
int x,y;
friend bool operator <(node a,node b)
{
return a.y>b.y;
}
}now;
long long ans;
int main()
{
int m,n,a,b,t;
while(~scanf("%d%d",&n,&m))
{
if(n>m)
{
printf("-1\n");
continue;
}
ans=0,t=n;
memset(vis,false,sizeof(vis));
priority_queue<node>q;
for(int i=0;i<n;i++)
scanf("%d",&s[i]);
sort(s,s+n);
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
now.x=a,now.y=b;
q.push(now);
}
while(!q.empty())
{
now=q.top();
q.pop();
int j=upper_bound(s,s+n,now.x)-s;
for(int i=j-1;i>=0;i--)
{
if(!vis[i])
{
t--;
vis[i]=true;
ans+=(long long)(now.y);
break;
}
}
}
if(t) printf("-1\n");
else printf("%lld\n",ans);
}
}
用multiset存每组的人数,每次放入地点就把这组人删掉,这样会快一些。
#include<stdio.h>
#include<stdlib.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
multiset<int>st;
struct node
{
int x,y;
friend bool operator <(node a,node b)
{
return a.y>b.y;
}
}now;
priority_queue<node>q;
LL ans;
int main()
{
ans=0;
int n,m,a,b;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%d",&a);
st.insert(a);
}
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
now.x=a,now.y=b;
q.push(now);
}
multiset<int>::iterator it;
while(!q.empty())
{
now=q.top();
q.pop();
it=st.upper_bound(now.x);
if(it==st.begin()) continue;
it--;
st.erase(it);
ans+=now.y;
}
if(st.size()!=0) printf("-1\n");
else printf("%lld\n",ans);
}
用set:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
set<int> mp;
int num[100005];
typedef struct p
{
int num;
int price;
} P;
P s[100005];
bool cmp(P a,P b)
{
return a.price<b.price;
}
int main()
{
memset(num,0,sizeof(num));
int n,m,a;
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
{
scanf("%d",&a);
mp.insert(a);
num[a]++;
}
for(int i=0; i<m; i++)
scanf("%d%d",&s[i].num,&s[i].price);
sort(s,s+m,cmp);
if(m<n) printf("-1\n");
else
{
int ans=0;
set<int>::iterator it;
for(int i=0; i<m; i++)
{
it=mp.upper_bound(s[i].num);
if(it==mp.begin())
continue;
it--;
ans+=s[i].price;
num[*it]--;
if(num[*it]==0)
mp.erase(*it);
}
if(mp.size()==0) printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}