1. 程式人生 > >【演算法競賽進階指南】BZOJ3032七夕祭

【演算法競賽進階指南】BZOJ3032七夕祭

兩次環形分牌

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=100010;
int x[maxn],y[maxn];
long long s1[maxn],s2[maxn];

int main(){
    int N,M,T;
    cin>>N>>M>>T;
    int a,b;
    for(int i=1;i<=T;i++){
        cin>>a>>b;
        x[a]++;
        y[b]++;
    }
    
    if(T%M!=0 && T%N!=0){cout<<"impossible\n";return 0;}
    
    for(int i=1;i<=N;i++) x[i]-=T/N;
    for(int i=1;i<=M;i++) y[i]-=T/M;
    
    long long ans=0;
    
    if(T%N==0){
        for(int i=1;i<=N;i++) s1[i]=s1[i-1]+x[i];
        sort(s1+1,s1+N+1);
        long long t=s1[(N+1)>>1];
        for(int i=1;i<=N;i++){
            if(t-s1[i]>=0) ans=ans+t-s1[i];
            else ans=ans+s1[i]-t;
        }
    }
    if(T%M==0){
        for(int i=1;i<=M;i++) s2[i]=s2[i-1]+y[i];
        sort(s2+1,s2+M+1);
        long long t=s2[(M+1)>>1];
        for(int i=1;i<=M;i++){
            if(t-s2[i]>=0) ans=ans+t-s2[i];
            else ans=ans+s2[i]-t;
        }
    }
    
    if(T%N==0 && T%M==0) cout<<"both ";
    else if(T%N==0) cout<<"row ";
    else cout<<"column ";
    cout<<ans<<"\n";
    return 0;
}