CF1148E Earth Wind and Fire

一、题目

点此看题

二、解法

首先排序,分配数如果交叉,那么肯定有不交叉的方案能够替换(这道题不要求操作数最小)。

这说明排序后数组对应位置上的数最后也是对应起来的,这样问题就简化了。先判断无解,如果总和对不上,无解, s s k k 个的和比 t t k k 个的和大的话,无解(看作一个整体,只可能从后面分配到前面)

然后维护两个指针,暴力分配即可,最多分配 2 n 2n 次。

#include <cstdio>
#include <algorithm>
using namespace std;
const int M = 300005;
int read()
{
    int num=0,flag=1;
    char c;
    while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;
    while(c>='0'&&c<='9')num=(num<<3)+(num<<1)+(c^48),c=getchar();
    return num*flag;
}
int n,m,c[M],x[M],y[M],z[M];
long long sa,sb;
struct node
{
	int x,y;
	bool operator < (const node &b) const
	{
		return x<b.x;
	}
}a[M],b[M];
signed main()
{
	n=read();
	for(int i=1;i<=n;i++)
	{
		a[i].x=read();
		a[i].y=i;
	}
	for(int i=1;i<=n;i++)
	{
		b[i].x=read();
		b[i].y=i;
	}
	sort(a+1,a+1+n);
	sort(b+1,b+1+n);
	for(int i=1;i<=n;i++)
	{
		sa+=a[i].x;
		sb+=b[i].x;
		c[i]=a[i].x-b[i].x;
		if(sa>sb)
		{
			puts("NO");
			return 0;
		}
	}
	if(sa!=sb)
	{
		puts("NO");
		return 0;
	}
	puts("YES");
	for(int i=1,j=1;i<=n;i++)
	{
		while(c[i]<0)
		{
			m++;
			while(c[j]<=0) j++;
			int t=min(-c[i],c[j]);
			x[m]=a[i].y;
			y[m]=a[j].y;
			z[m]=t;
			c[i]+=t;
			c[j]-=t;
		}
	}
	printf("%d\n",m);
	for(int i=1;i<=m;i++)
		printf("%d %d %d\n",x[i],y[i],z[i]);
}

猜你喜欢

转载自blog.csdn.net/C202044zxy/article/details/107483188
今日推荐