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<=n<=1000,0<=m<=1000, sum of n over all testcases <=2000, sum of m over all testcases <=2000.
0<=a[i],b[i]<=n.
1<=l[i]<=r[i]<=n.
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
Hint
题意
给你a[i]数组,给你b[i]数组
然后有m次交换,这m次交换是依次进行的,每次给你一个区间,就代表这个区间可以随意互换。
问你最后能不能得到B区间。
题解:
网络流是错的,虽然网络流能AC,但是这个做法显然是错的。
正解应该是贪心,对于最左边的值,那么他一定对应着在B[i]数组中与他相同的,且最左边的数。
根据这个,贪心的去扫一遍就好了,其实就是不断排序,为什么?
因为排序之后,一定会使得从目标到结束状态花费变得最小。
代码
#include <bits/stdc++.h>
#define rep(a,b,c) for(int (a)=(b);(a)<=(c);++(a))
#define drep(a,b,c) for(int (a)=(b);(a)>=(c);--(a))
#define pb push_back
#define mp make_pair
#define sf scanf
#define pf printf
#define two(x) (1<<(x))
#define clr(x,y) memset((x),(y),sizeof((x)))
#define dbg(x) cout << #x << "=" << x << endl;
const int mod = 1e9 + 7;
int mul(int x,int y){return 1LL*x*y%mod;}
int qpow(int x , int y){int res=1;while(y){if(y&1) res=mul(res,x) ; y>>=1 ; x=mul(x,x);} return res;}
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
using namespace std;
const int maxn = 1000 + 15;
int a[maxn],b[maxn],ptr[maxn],l[maxn],r[maxn];
vector < int > po[maxn];
int main(int argc,char *argv[]){
int T=read();
while(T--){
int N=read(),M=read();
rep(i,0,N){
po[i].clear();
ptr[i]=0;
}
rep(i,1,N){
a[i]=read();
}
rep(i,1,N){
b[i]=read();
po[b[i]].pb(i);
}
bool ans = true;
rep(i,1,N){
if(ptr[a[i]] == po[a[i]].size()) ans = false;
else a[i]=po[a[i]][ptr[a[i]]++];
}
rep(i,1,M) l[i]=read(),r[i]=read();
if( ans == false ) pf("No\n");
else{
rep(i,1,M) sort(a+l[i],a+r[i]+1);
rep(i,1,N) if(a[i]!=i) ans = false;
if(ans == true) pf("Yes\n");
else pf("No\n");
}
}
return 0;
}