个人博客题意:存在两个不同行r1,r2和两个不同列c1,c2。是否存在r1,r2和从c1,c2使得(r1,c1)和(r2,c1)相同。
分析:
可以直接写一个四重循环枚举出r1,r2,c1,c2。理论上是可以的,但实际上却会TLE超时。
解决方法是只枚举c1,c2,然后从上往下扫描各行。每次碰到一个新的行r,就把对应c1,c2的内容作为一个二元组存到一个map里,然后如果map的键值已经存在这个二元组,该二元组映射到的就是所要求的r1,而当前行就是r2。
细节问题:如何表示由c1,c2两列组成的二元组?一种方法是直接用两个字符串拼成一个长字符串(中间用一个其他地方不可能出现的字符分隔),但是速度比较慢,(因为在map中查找元素时需要进行字符串比较操作)。更值得推荐的方法是在主循环之前先做一个预处理—给所有字符串分配一个编号,则整个数据库中每个单元格都变成了整数,上述二元组就变成了两个整数。
个人博客代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
#include<iostream>
#include<cstdio>
#include<map>
#include<string>
#include<vector>
using
namespace
std;
const
int
ROW = 10000 + 10;
const
int
COL = 10 + 5;
int
n,m;
map<string,
int
> IDcache;
vector<string> Strcache;
vector<
int
> Text[ROW];
//保存处理后的文本,每个字符串都替换成一个编号
struct
node
{
int
x,y;
node(
int
x,
int
y):x(x),y(y) { }
bool
operator < (
const
node& r)
const
{
return
x<r.x || x==r.x&&y<r.y; }
};
map<node,
int
> data;
int
ID_alloc(string str)
{
if
(IDcache.count(str))
return
IDcache[str];
Strcache.push_back(str);
return
IDcache[str] = Strcache.size()-1;
}
void
read()
{
string str;
char
ch =
getchar
();
for
(
int
i=0;i<n;i++)
{
for
(;;)
{
ch =
getchar
();
if
(ch==
'\n'
||ch==
'\r'
) {
if
(!str.empty()) Text[i].push_back(ID_alloc(str));
str.clear();
break
;
}
if
(ch!=
','
) str += ch;
else
{ Text[i].push_back(ID_alloc(str)); str.clear();}
}
}
}
void
solve()
{
int
x,y,c1,c2;
for
(c1=0;c1<m;c1++)
{
for
(c2=c1+1;c2<m;c2++)
{
data.clear();
for
(
int
r=0;r<n;r++)
{
x = Text[r][c1]; y = Text[r][c2];
node p(x,y);
if
(!data.count(p)) data[p] = r;
else
{
cout<<
"NO"
<<endl;
cout<<data[p]+1<<
" "
<<r+1<<endl<<c1+1<<
" "
<<c2+1<<endl;
return
;
}
}
}
}
cout<<
"YES"
<<endl;
}
int
main() {
//freopen("1592.txt","r",stdin);
while
(cin>>n>>m)
{
read();
solve();
for
(
int
i=0;i<n;i++) Text[i].clear();
IDcache.clear(); Strcache.clear();
//data.clear();
}
return
0;
}
|