優先佇列貪心
阿新 • • 發佈:2019-01-05
#include<iostream>
#include<cstring>
#include<math.h>
#include<cstdio>
#include<algorithm>
#define N 6005
#define INF 0x3f3f3f3f
#include<map>
#include<string>
#include<queue>
#include<vector>
#include<set>
#define mod 1000000007
double pi=acos(-1.0);
typedef long long ll;
using namespace std;
typedef pair<ll,int > pr;
priority_queue<pr,vector<pr>,greater<pr> > q[4];
ll p[200050],a[200050],b[200050];
int vis[200050];
int m,c,n;
int main(){
memset(vis,0,sizeof(vis));
cin>>n;
for(int i=0;i<n;i++)
{
scanf("%I64d",&p[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d ",&a[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
for(int i=0;i<n;i++)
{
q[a[i]].push(make_pair(p[i],i));
q[b[i]].push(make_pair(p[i],i));
}
cin>>m;
for(int i=0;i<m;i++)
{
scanf("%d",&c);
int flag=0;
while(!q[c].empty())
{
if(vis[q[c].top().second]) q[c].pop();
else
{
flag=1;
break;
}
}
if(!flag)
{
printf("-1 ");
continue;
}
pr temp=q[c].top();
printf("%I64d ",temp.first);
q[c].pop();
vis[temp.second]=1;
}
return 0;
}
2、cf 3D D. Least Cost Bracket Sequence
把所有的‘?’都換成右括號,放進佇列,當不滿足對稱時選cost最小的就可以了
程式碼:
#include<iostream>
#include<cstring>
#include<math.h>
#include<cstdio>
#include<algorithm>
#define N 6005
#define INF 0x3f3f3f3f
#include<map>
#include<string>
#include<queue>
#include<vector>
#include<set>
#define mod 1000000007
double pi=acos(-1.0);
typedef long long ll;
using namespace std;
char s[50050];
int a,b;
typedef pair<int,int> p;
int main(){
scanf("%s",s);
int m=0,zuo=0;
ll ans=0;
int len=strlen(s);
if(len&1||s[0]==')')
{
printf("-1\n");
return 0;
}
priority_queue<p> q;
for(int i=0;i<len;i++)
{
if(s[i]=='(') zuo++;
else if(s[i]==')') zuo--;
else
{
cin>>a>>b;
ans+=b;
s[i]=')';
q.push(make_pair(b-a,i));
zuo--;
}
if(zuo<0)
{
if(q.empty())
{
printf("-1\n");
return 0;
}
p temp=q.top();
q.pop();
zuo+=2;
ans-=temp.first;
s[temp.second]='(';
}
}
if(zuo>0)
{
printf("-1\n");
return 0;
}
else printf("%I64d\n%s\n",ans,s);
return 0;
}
3、ZOJ 3699
經典的加油問題
程式碼:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
const int maxn = 200005;
const int inf = 1111111111;
long long q[maxn],head,tail,cost[maxn];
long long p[maxn];
int main()
{
//freopen("in.txt","r",stdin);
int ca,n,m,use[maxn];
int u,v;
long long w;
bool flag;
scanf("%d",&ca);
while(ca--)
{
scanf("%d%d",&n,&m);
flag = 1;
for(int i = 1; i <= n; i++)
{
scanf("%d%d%d",&u,&v,&p[i]);
w=(long long)u*v;
if(w>m) flag = 0;
else cost[i]=u*v;
}
if(flag == 0)
{
printf("Impossible\n");
continue;
}
head = tail = 0;
long long ans = 0;
long long gas=0;
for(int i = 1; i <= n; i++)
{
while(head<tail&&p[i]<p[q[tail-1]]) gas-=use[--tail];
use[tail]=m - gas;
q[tail++]=i;
//cout<<gas<<" "<<m-gas<<endl;
gas = m - cost[i];
//cout<<gas<<endl;
while(cost[i])
{
if(use[head]<=cost[i])
{
cost[i]-=use[head];
ans+=use[head]*p[q[head]];
head++;
}
else
{
use[head]-=cost[i];
ans+=cost[i]*p[q[head]];
cost[i]=0;
}
}
}
cout<<ans<<endl;
}
return 0;
}