Organizing Containers of Balls

David has containers and different types of balls, both of which are numbered from to . The distribution of ball types per container are described by an matrix of integers, , where each is the number of balls of type in container . For example, consider the following diagram for :
In a single operation, David can swap two balls located in different containers (i.e., one ball is moved from container to and the other ball is moved from to ).
For example, the diagram below depicts a single swap operation:
David wants to perform some number of swap operations such that both of the following conditions are satisfied:
- Each container contains only balls of the same type.
- No two balls of the same type are located in different containers.
You must perform queries where each query is in the form of a matrix, . For each query, print Possible
on a new line if David can satisfy the conditions above for the given matrix; otherwise, print Impossible
instead.
Input Format
The first line contains an integer denoting (the number of queries). The subsequent lines describe each query in the following format:
- The first line contains an integer denoting (the number of containers and ball types).
- Each line of the subsequent lines contains space-separated integers describing row in matrix .
Constraints
Scoring
- For of score, .
- For of score, .
Output Format
For each query, print Possible
on a new line if David can satisfy the conditions above for the given matrix; otherwise, print Impossible
instead.
Sample Input 0
2
2
1 1
1 1
2
0 2
1 1
Sample Output 0
Possible
Impossible
Explanation 0
We perform the following queries:
- The diagram below depicts one possible way to satisfy David's requirements for the first query:
Thus, we printPossible
on a new line. - The diagram below depicts the matrix for the second query:
No matter how many times we swap balls of type and between the two containers, we'll never end up with one container only containing type and the other container only containing type . Thus, we printImpossible
on a new line.
题目链接:https://www.hackerrank.com/contests/hourrank-17/challenges/organizing-containers-of-balls
题目的意思不难理解,就是说通过交换是否可以每个容器里只放一种球。
这个题我一开始想错了,默认了第一个容器里只能放第一类球,所以wa了一发,其实他只要求了同一类球只能放在一个容器里,并没有说是哪个容器,我们需要两个数组,用代码讲。
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int a[101][101];
long long b[101];//横着计数
long long c[101];//竖着计数
int main(){
int t;
scanf("%d",&t);
while(t--){
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
b[i]+=a[i][j];
c[j]+=a[i][j];
}
}
bool vis[101];//记录第几个容器是否被用过
memset(vis,false,sizeof(vis));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(b[i]-a[i][j]==c[j]-a[i][j]&&!vis[j]){
vis[j]=true;
}
}
}
int i;
for(i=1;i<=n;i++){
if(!vis[i])
break;
}
if(i==n+1){
cout<<"Possible"<<endl;
}
else{
cout<<"Impossible"<<endl;
}
}
return 0;
}