题目链接:https://cn.vjudge.net/problem/UVA-1592#author=0
题目大意:输入一个n行m列的数据库(1=<n<=10000, 1=<m<=10),是否存在两个不同r1,r2和两个不同列c1,c2,使得这两行和这两列相同(即(r1,c2)和(r2,c1)相同,(r1,c2)和(r2,c2)相同)。
分析:使用容器map将每个字符串设置一个编号,要牢记这种思路,这样在查找时只比较id即可,不用比较字符串。还要注意getline 并不忽略行开头的换行符。只要 getline 遇到换行符,即便它是输入的第一个字符,getline 也将停止读入并返回需要吸收回车符!!
代码:
#include <bits/stdc++.h>
using namespace std;
const int mrow = 10000+10;
const int mcol = 10+10;
string first[mrow];
string init[mrow][mcol];
int num[mrow][mcol];
map<string, int> ID;
int row, col;
void Init() {
int cnt = 0;
for(int i = 0; i < row; i++) {
int index1 = 0, index2 = 0;
for(int j = 0; j < col-1; j++) {
index2 = first[i].find(',', index1);
init[i][j] = first[i].substr(index1, index2-index1);
if(j==col-2)
init[i][j+1] = first[i].substr(index2+1);
index1 = index2+1;
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(ID.count(init[i][j]))
num[i][j] = ID[init[i][j]];
else num[i][j] = ID[init[i][j]] = cnt++;
}
}
}
void Find() {
for(int i = 0; i < row-1; i++) {
for(int j = i+1; j < row; j++) {
int flag = 0;
int arr[10];
for(int k = 0; k < col; k++) {
if(num[i][k]==num[j][k]) {
//保证为同一列中寻找
arr[flag++] = k;
if(flag==2) {
cout<<"NO"<<endl;
cout<<i+1<<" "<<j+1<<endl;
cout<<arr[0]+1<<" "<<arr[1]+1<<endl;
return;
}
}
}
}
}
cout << "YES" << endl;
}
int main() {
freopen("i.txt", "r", stdin);
while(cin >> row >> col) {
memset(num, 0, sizeof(num));
string str;
getchar();
for(int i = 0; i < row; i++)
getline(cin, first[i]);
Init();
Find();
ID.clear();
}
return 0;
}