hackerrank Ticket
题意:n个人排队买票,要把他们拆成k条队到k个窗口买,可以有队伍为空,每条队的顺序保持拆之前的顺序。如果某人和他前一个人买的票相同,就可以打八折,求最小花费。
题解:拆成k条队意味着只有[n-k,n-1]组前后关系,那么可以转成二分图最大权匹配,流的时候限制流量在[n-k,n-1]间就可以了。
#include<map> #include<queue> #include<string> #include<cstdio> #include<cstring> #include<algorithm> #define MAXN 5300 #define MAXM 35000 using namespace std; struct na{ int y,z,f,ne; }; int n,m,k,l[MAXN],r[MAXN],num=0,p,ch,S,T,dis[MAXN],mi[MAXN],ro[MAXN],qi[MAXN],no,v[MAXN],R[MAXN],Ro[501][501],li[501]; na b[MAXM]; bool bo[MAXN]; const int INF=1e9; int mmh=0,an=0; queue<int> q; inline int min(int x,int y){return x>y?y:x;} inline void spfa(){ register int i; q.push(S); bo[S]=1; for (i=0;i<=no;i++) dis[i]=INF; mi[S]=INF;dis[S]=0;dis[T]=INF; while(!q.empty()){ int k=q.front();q.pop();bo[k]=0; if (k==T) continue; for (i=l[k];i;i=b[i].ne){ if (b[i].z>0&&dis[b[i].y]>b[i].f+dis[k]){ dis[b[i].y]=b[i].f+dis[k]; mi[b[i].y]=min(mi[k],b[i].z); ro[b[i].y]=i; qi[b[i].y]=k; if (!bo[b[i].y]){ bo[b[i].y]=1; q.push(b[i].y); } } } } } inline int read(){ p=0;ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') p=p*10+ch-48, ch=getchar(); return p; } inline void add(int x,int y,int z,int f){ num++; if (l[x]==0) l[x]=num;else b[r[x]].ne=num; b[num].y=y;b[num].z=z;b[num].f=f;r[x]=num; } inline void in(int x,int y,int z,int f){ add(x,y,z,f);add(y,x,0,-f); } map<string,int> ma; char s[1000]; int main(){ register int i,j; n=read();m=read();k=read();S=0;no=T=n+n+1; for (i=1;i<=k;i++){ scanf("%s",s); ma[string(s)]=i; v[i]=read(); } for (i=1;i<=n;i++) scanf("%s",s),R[i]=ma[string(s)],mmh+=v[R[i]],in(S,i,1,0),in(i+n,T,1,0); for (i=1;i<=n;i++) for (j=i+1;j<=n;j++) in(i,j+n,1,R[i]==R[j]?-v[R[j]]:0),Ro[i][j]=num-1; for (int f=0;;f++){ spfa(); if (dis[T]==INF) break; if (dis[T]>=0&&f>=n-m) break; an+=mi[T]*dis[T]; for (i=T;i;i=qi[i]) b[ro[i]].z-=mi[T],b[((ro[i]-1)^1)+1].z+=mi[T]; } printf("%lf\n",1.*mmh+0.2*an); int s=0; for (i=1;i<=n;i++){ for (j=1;j<i;j++) if (b[Ro[j][i]].z==0) break; if (j==i) li[i]=++s;else li[i]=li[j]; printf("%d\n",li[i]); } }