头像

欢迎来到我的博客

分享题解与总结

P1056 排座椅

P1056 排座椅

P1056 排座椅 - 洛谷

题目含义:

\(M\)行\(N\)列的教室,\(M\times N\)个同学的座位已经固定

有\(D\)对同学会交头接耳

老师想通过划分通道的方式,用通道隔开说话的同学

教室设置了\(K\)条横向通道,\(L\)条纵向通道,如何排布通道,才能让交头接耳的同学对尽可能少?

思路:

贪心+排序

利用有限的通道,尽可能 划开 更多对交头接耳的同学

统计每行/列通道可以划开的学生总数,按照降序排序,取出前\(K/L\)大的行/列通道

通道编号如图:

image-20261018181419824

假设row[x]表示第x行通道,输入\(D\)对\((x,y),(p,q)\),设\(x<=p\),beside(?1,?2)表示?1与?2相邻:

row[x]++ \(\Leftrightarrow\) beside(x,p)==true

col[y]++ \(\Leftrightarrow\) beside(y,q)==true

注:答案要求按照编号从小到大输出,列尾没有空格

代码:

const int N=1005;
int m,n,k,l,d;
struct Row{
    int cnt,idx;
    bool operator<(const Row& r) const{
        return this->cnt > r.cnt;
    }
};
struct Col{
    int cnt,idx;
    bool operator<(const Col& c) const{
        return this->cnt > c.cnt;
    }
};
Row row[N];
Col col[N];

inline bool beside(int a1,int a2){
    return (a1+1==a2)||(a2+1==a1);
}

int main()
{
    cin>>m>>n>>k>>l>>d;
    int x,y,p,q;
    //统计
    for(int i=0;i<=m+1;++i){row[i]={0,i};}
    for(int j=0;j<=n+1;++j){col[j]={0,j};}
    for(int i=1;i<=d;++i){
        cin>>x>>y>>p>>q;
        int sm_x=min(x,p),sm_y=min(y,q);
        bool rtag=beside(x,p),ctag=beside(y,q);
        if(rtag) row[sm_x].cnt++;
        if(ctag) col[sm_y].cnt++;
    }
    sort(row+1,row+m+1);
    sort(col+1,col+n+1);
    vector<int> ansr,ansc;
    for(int i=1;i<=k;++i) ansr.push_back(row[i].idx);
    sort(ansr.begin(),ansr.end());
    for(int i=1;i<=l;++i) ansc.push_back(col[i].idx);
    sort(ansc.begin(),ansc.end());
    for(int i=0;i<k;++i) cout<<ansr[i]<<" \n"[i==k-1];
    for(int j=0;j<l;++j) cout<<ansc[j]<<" \n"[j==l-1];
    return 0;
}
posted @ 2026-10-18 18:22  king_steph1209  阅读(11)  评论(0)    收藏  举报