本文主要是介绍UVA1592 DataBase 解题报告,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
UVA1592 DataBase 解题报告
题目链接
https://vjudge.net/problem/UVA-1592
题目大意
输入一个n行m列的数据库(1≤n≤10000,1≤i≤10),是否存在两个不同行r1,r2和两个不同列c1,c2,使得这两行和这两列相同(即(r1,c1)和(r2,c1)相同,(r1,c2)和(r2,c2)相同)。
解题思路
直接写一个四重循环枚举r1,r2,c1,c2可以吗?理论上可以,实际上却行不通。枚举量太大,程序会执行相当长的时间,最终获得TLE(超时)。解决方法是只枚举c1和c2,然后从上到下扫描各行。每次碰到一个新的行r,把c1,c2两列的内容作为一个二元组存到一个map中。如果map的键值中已经存在这个二元组,该二元组映射到的就是所要求的r1,而当前行就是r2。
这里有一个细节问题:如何表示由c1,c2两列组成的二元组?一种方法是直接用两个字符串拼成一个长字符串(中间用一个其他地方不可能出现的字符分隔),但是速度比较慢(因为在map中查找元素时需要进行字符串比较操作)。更值得推荐的方法是在主循环之前先做一个预处理——给所有字符串分配一个编号,则整个数据库中每个单元格都变成了整数,上述二元组就变成了两个整数。
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define endl '\n';
const int maxn = 1e4 + 10;
const int INF = 0x3fffffff;
const int mod = 1e9 + 7;
int n, m;
string str[maxn][15];
map<string, int> idCache;
map<int, string> strCahe;void Init(string s, int r) {string tmp = "";int c = 1;for (int i = 0; i < s.size(); i++) {if (s[i] == ',') {str[r][c++] = tmp;tmp = "";} else {tmp += s[i];}}str[r][c] = tmp;
}int getID(string s) {if (idCache.count(s))return idCache[s];int num = idCache.size() + 1;idCache[s] = num;strCahe[num] = s;return num;
}void solve() {cin.get();idCache.clear();strCahe.clear();for (int i = 1; i <= n; i++) {string s;getline(cin, s);Init(s, i);}for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {string s = str[i][j];// cout << s << ", ";getID(s);}// cout << endl;}map<pair<int, int>, int> mp;for (int c1 = 1; c1 <= m; c1++) {for (int c2 = c1 + 1; c2 <= m; c2++) {for (int r = 1; r <= n; r++) {auto p = make_pair(getID(str[r][c1]), getID(str[r][c2]));if (mp.count(p)) {cout << "NO\n";cout << mp[p] << " " << r << endl;cout << c1 << " " << c2 << endl;return;}mp[p] = r;}}}cout << "YES\n";
}int main() {ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);cout << fixed;cout.precision(18);while (cin >> n >> m)solve();return 0;
}
这篇关于UVA1592 DataBase 解题报告的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!