HDU 5821 Ball (贪心)

时间:2023-03-09 14:53:25
HDU 5821 Ball (贪心)

Ball

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5821

Description


ZZX has a sequence of boxes numbered 1,2,...,n. Each box can contain at most one ball.
You are given the initial configuration of the balls. For 1≤i≤n, if the i-th box is empty then a[i]=0, otherwise the i-th box contains exactly one ball, the color of which is a[i], a positive integer. Balls with the same color cannot be distinguished.
He will perform m operations in order. At the i-th operation, he collects all the balls from boxes l[i],l[i]+1,...,r[i]-1,r[i], and then arbitrarily put them back to these boxes. (Note that each box should always contain at most one ball)
He wants to change the configuration of the balls from a[1..n] to b[1..n] (given in the same format as a[1..n]), using these operations. Please tell him whether it is possible to achieve his goal.

Input


First line contains an integer t. Then t testcases follow.
In each testcase: First line contains two integers n and m. Second line contains a[1],a[2],...,a[n]. Third line contains b[1],b[2],...,b[n]. Each of the next m lines contains two integers l[i],r[i].
1

Output


For each testcase, print "Yes" or "No" in a line.

Sample Input


5
4 1
0 0 1 1
0 1 1 1
1 4
4 1
0 0 1 1
0 0 2 2
1 4
4 2
1 0 0 0
0 0 0 1
1 3
3 4
4 2
1 0 0 0
0 0 0 1
3 4
1 3
5 2
1 1 2 2 0
2 2 1 1 0
1 3
2 4

Sample Output


No
No
Yes
No
Yes

Source


2016 Multi-University Training Contest 8


##题意:

有N个盒子,每个盒子最多装一个球. 球的颜色不一定相同.
现在要进行m次区间操作:
每次操作 [l, r] 后可以随意将区间内的球重新分配回去.
问经过上述操作后是否有可能达到给定的状态.


##题解:

贪心.
为每个球标记它在最终结果中的序号. 对于颜色相同的球:左边的尽量分配小的序号.
对于m次区间操作,就将区间[l,r]中的球按最终序号排序.
每次排序都相当于让区间中的球向它们的最终位置更近一步.
最终再比较是否每个球都到位即可.

官方题解:
假设有4个红球,初始时从左到右标为1,2,3,4。那么肯定存在一种方案,使得最后结束时红球的顺序没有改变,也是1,2,3,4。 那么就可以把同色球都写成若干个不同色球了。所以现在共有n个颜色互异的球。按照最终情况标上1,2,。。,n的序号,那么贪心的来每次操作就是把一个区间排序就行了。


##代码:
``` cpp
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define LL long long
#define eps 1e-8
#define maxn 1010
#define mod 100000007
#define inf 0x3f3f3f3f
#define mid(a,b) ((a+b)>>1)
#define IN freopen("in.txt","r",stdin);
using namespace std;

typedef pair<int,int> pii;

pii ball[maxn];

int main(int argc, char const *argv[])

{

//IN;

int t; cin >> t;
while(t--)
{
int n, m;
scanf("%d %d", &n,&m);
for(int i=1; i<=n; i++) {
int x; scanf("%d", &x);
ball[i] = make_pair(0, x);
}
for(int i=1; i<=n; i++) {
int color; scanf("%d", &color);
for(int j=1; j<=n; j++) {
if(ball[j].second == color && !ball[j].first) {
ball[j].first = i;
break;
}
}
} while(m--) {
int l,r; scanf("%d %d", &l, &r);
sort(ball+l, ball+r+1);
} bool flag = 1;
for(int i=1; i<=n; i++) {
if(ball[i].first != i) {
flag = 0; break;
}
} if(flag) puts("Yes");
else puts("No");
} return 0;

}