PAT 2020年春季 7-3 Safari Park (25 分)
A safari park(野生动物园)has K species of animals, and is divided into N regions. The managers hope to spread the animals to all the regions, but not the same animals in the two neighboring regions. Of course, they also realize that this is an NP complete problem, you are not expected to solve it. Instead, they have designed several distribution plans. Your job is to write a program to help them tell if a plan is feasible.
Input Specification:
Each input file contains one test case. For each case, the first line gives 3 integers: N (0<N≤500), the number of regions; R (≥0), the number of neighboring relations, and K (0<K≤N), the number of species of animals. The regions and the species are both indexed from 1 to N.
Then R lines follow, each gives the indices of a pair of neighboring regions, separated by a space.
Finally there is a positive M (≤20) followed by M lines of distribution plans. Each plan gives N indices of species in a line (the i-th index is the animal in the i-th rigion), separated by spaces. It is guaranteed that any pair of neighboring regions must be different, and there is no duplicated neighboring relations.
Output Specification:
For each plan, print in a line Yes if no animals in the two neighboring regions are the same, or No otherwise. However, if the number of species given in a plan is not K, you must print Error: Too many species. or Error: Too few species. according to the case.
Sample Input:
复制6 8 3
2 1
1 3
4 6
2 5
2 4
5 4
5 6
3 6
5
1 2 3 3 1 2
1 2 3 4 5 6
4 5 6 6 4 5
2 3 4 2 3 4
2 2 2 2 2 2
Sample Output:
Yes
Error: Too many species.
Yes
No
Error: Too few species.
实现思路:
题意是把K种动物分配到N个区域,但是相邻的两个区域不能有相同物种,然后给出一些相邻区域,明显就是一道图论题,用邻接表保存下邻边关系,其实和之前的PAT1154一模一样,就是判断相邻两个结点的物种索引号都不同就输出yes,少了输出Too few species,超过K种Too many species。
AC代码:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
const int MAXN=520;
int n,r,k;
vector<int> G[MAXN];
int main() {
int a,b;
cin>>n>>r>>k;
while(r--) {
scanf("%d%d",&a,&b);
G[a].push_back(b);
G[b].push_back(a);
}
int m,sq[MAXN];
cin>>m;
while(m--) {
unordered_map<int,int> mp;
bool tag=true;
for(int i=1; i<=n; i++) {
scanf("%d",&sq[i]);
mp[sq[i]]=1;
}
if(mp.size()==k) {
for(int i=1; i<=n; i++) {
if(!tag) break;
for(int j=0; j<G[i].size(); j++) {
int id=G[i][j];
if(sq[i]==sq[G[i][j]]) {
tag=false;
break;
}
}
}
if(!tag) printf("No");
else printf("Yes");
} else if(mp.size()>k) {
printf("Error: Too many species.");
} else printf("Error: Too few species.");
printf("\n");
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
· 瞧瞧别人家的限流,那叫一个优雅!
· 1.net core 工作流WorkFlow流程(介绍)
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 面试官:如果某个业务量突然提升100倍QPS你会怎么做?
· .NET 平台上的开源模型训练与推理进展