cf1551b2/Wonderful Coloring - 2(不涉及STL,但代码还会wa)

该代码解决了一个问题,其中涉及到对数组元素进行染色。首先对数组进行两次排序,然后遍历数组,将数量大于等于颜色数量n的元素染色,接着处理数量小于n的元素,确保所有元素被均匀分配颜色。最后,输出染色后的元素颜色。
摘要由CSDN通过智能技术生成

题目链接                    Problem - B2 - Codeforces

变量 m 为数组长度,n为颜色数量 

 我的思路  就是把大于等于 n 的一种元素献给染上颜色

                  然后在继续遍历小于 n 的元素 

思路理清后,首先我先将数组里的数按照元素个数

我是用了两次 sort 将其排好序

bool cmp(st a,st b)//先将数给排一边,不排的话下一步排序会排 出错的
{
	return a.num<b.num;
}
bool cmpt(st aa,st bb)//a是记录元素个数 
{
	return a[aa.num]>a[bb.num];
}

//main中其中一部分
        int m,n;	cin>>m>>n;
		memset(a,0,sizeof a);
		for(int i=1;i<=m;i++)
		{
			int x;	cin>>x;
			U[i].num=x;U[i].idx=i;
			a[x]++;U[i].cl=0;
		}
		
		
		sort(U+1,U+1+m,cmp);
		sort(U+1,U+1+m,cmpt);

 第二步,开始遍历元素,并对其染色 

 

        int i;
		for(i=1;i<=m;)
		{
			int x=a[U[i].num];
			if(x>=n)
			{
				for(int t=1;t<=n;t++)
					U[t+i-1].cl=t;
				
				i+=x;
			}
			else	break;
		}
        //上边是对大/等于 n 的染色
        //下面是对 小于  n 的染色
		int w=0;
		for(int t=i;t<=m-(m-i+1)%n;t++)
		{
			U[t].cl=++w;
			w=w%n;
		}
        

最后就是输出

wa test 3 120组代码

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int a[N];
struct st
{
	int num,idx,cl;
}U[N];

bool cmp(st a,st b)
{
	return a.num<b.num;
}
bool cmpt(st aa,st bb)
{
	return a[aa.num]>a[bb.num];
}
bool cmpx(st a,st b)
{
	return a.idx<b.idx;
}


int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		int m,n;	cin>>m>>n;
		memset(a,0,sizeof a);
		for(int i=1;i<=m;i++)
		{
			int x;	cin>>x;
			U[i].num=x;U[i].idx=i;
			a[x]++;U[i].cl=0;
		}
		
		
		sort(U+1,U+1+m,cmp);
		sort(U+1,U+1+m,cmpt);
		
		
		int i;
		for(i=1;i<=m;)
		{
			int x=a[U[i].num];
			if(x>=n)
			{
				for(int t=1;t<=n;t++)
					U[t+i-1].cl=t;
				
				i+=x;
			}
			else	break;
		}
		int w=0;
		for(int t=i;t<=m-(m-i+1)%n;t++)
		{
			U[t].cl=++w;
			w=w%n;
		}
		
		sort(U+1,U+1+m,cmpx);
		for(i=1;i<=m;i++)
			cout<<U[i].cl<<' ';cout<<'\n';
	}
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值