浅析Pat 甲级1121. Damn Single(单身狗
题目:
“Damn Single (单身狗)” is the Chinese nickname for someone who is being single. You are supposed to find those who are alone in a big party, so they can be taken care of.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=50000), the total number of couples. Then N lines of the couples follow, each gives a couple of ID’s which are 5-digit numbers (i.e. from 00000 to 99999). After the list of couples, there is a positive integer M (<=10000) followed by M ID’s of the party guests. The numbers are separated by spaces. It is guaranteed that nobody is having bigamous marriage (重婚) or dangling with more than one companion.
Output Specification:
First print in a line the total number of lonely guests. Then in the next line, print their ID’s in increasing order. The numbers must be separated by exactly 1 space, and there must be no extra space at the end of the line.
Sample Input:
3
11111 22222
33333 44444
55555 66666
7
55555 44444 10000 88888 22222 11111 23333
Sample Output:
5
10000 23333 44444 55555 88888
分析:
1.couple之间的对应关系,可以选择二维数组或者map。选择数组的时候,行表示couple的个数,列有两个,一个为丈夫,一个为妻子。选择map是必须注意:一对couple(A,B),A为key必须对应B,同时B也应该为key,对应A.
2.查询是否单身时,可以按照夫妻数目进行第一重循环,丈夫和妻子同时在待查询的数组中时,把相应的夫妻删除。
3.通过二维数组和map可以做出来,但是超时!!!。因此不能这样做,选择哈希!!
分析2
1.这道题无非就是妻子与丈夫对应,丈夫与妻子对应。那么选择哈希,妻子中存丈夫,丈夫中存妻子。查询的数组也用哈希。
2.具体:开两个数组,一个存couple,一个存待查找的。
代码
#include <iostream>
#include <string>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
const int MAX = 100000;
string couple[MAX];
string peek[MAX];
int n;
cin>>n;
for (int i = 0; i < MAX; i++) {//初始化
couple[i]=" ";
peek[i] =" ";
}
for (int i = 0; i < n; i++) {
string s; cin>>s;
string ss; cin>>ss;
couple[atoi(s.c_str())] = ss;//对应关系存储
couple[atoi(ss.c_str())] = s;
}
int m;
cin>>m;
for (int i = 0; i < m; i++) {
string s;
cin>>s;
peek[atoi(s.c_str())] = s;
}
int sum = 0;
for (int i = 0; i < MAX; i++) {
if(!(peek[i]==" ")){
string s = couple[atoi(peek[i].c_str())];//根据couple查到另一方
if(!(s==" ")){
if(!(peek[atoi(s.c_str())]==" ")){//查找数组中有
peek[i]=" ";//查到置为空
peek[atoi(s.c_str())]=" ";//查到置为空
sum+=2;
}
}
}
}
cout<<m-sum<<endl;
string st="";
for (int i = 0; i < MAX; i++) {//输出
if(!(peek[i]==" ")){
st.append(peek[i]+" ");
}
}
cout<<st.substr(0,st.length()-1);
return 0;
}