JZOJ 3382. [noip 2013 simulation] Qixi Festival

Catalog:

Title:

Click to view title

Analysis:

First, exchanges in the same column only affect rows, and exchanges in the same row only affect columns. So we can consider row and column separately. I have a question when I do questions - will spatial structure affect exchange? If there are two favorite stalls in the same row, they cannot be exchanged. emmm, if I draw a picture by myself, I will find that I am worried too much.
If only rows (or columns) are considered, we naturally think of the ring uniform card model - the number of favorite stalls contained in each row (or column) is the initial value, two adjacent rows (or columns) can give each other, and the minimum number of stalls is required. Then, if we set up an unknown number, set up an equation, and draw a conclusion by using the absolute value inequality, we can use the median to solve it
Complexity O(nlogn + mlogm).

Code:

#pragma GCC optimize("O3")
#pragma G++ optimize("O3")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define LL long long
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
int x[110000],y[110000],ne[110000];
int main()
{
    int n=read(),m=read(),t=read();
    if(t%n==0&&t%m==0) printf("both ");
    else if(t%n==0) printf("row ");
    else if(t%m==0) printf("column ");
    else {printf("impossible ");return 0;}
    int a,b;
    for(int i=1;i<=t;i++)
      {
        a=read();b=read();
        x[a]++;y[b]++;
      }
    int e,mid;long long ans=0;
    if(t%n==0)
    {
        e=t/n;
        for(int i=1;i<=n;i++) x[i]-=e;
        for(int i=1;i<=n;i++)
          ne[i]=ne[i-1]+x[i];
        sort(ne+1,ne+1+n);
        mid=(n+1)/2;
        for(int i=1;i<=n;i++)
          ans+=(long long)abs(ne[i]-ne[mid]);
    }

    if(t%m==0)
    {
        memset(ne,0,sizeof(ne));
        e=t/m;
        for(int i=1;i<=m;i++) y[i]-=e;
        for(int i=1;i<=m;i++)
            ne[i]=ne[i-1]+y[i];
        sort(ne+1,ne+1+m);
        mid=(m+1)/2;
        for(int i=1;i<=m;i++)
          ans+=(long long)abs(ne[i]-ne[mid]);
    }
    printf("%lld",ans);
    return 0;
}

Posted by coolispaul on Sat, 15 Feb 2020 12:26:22 -0800