码迷,mamicode.com
首页 > 数据库 > 详细

UVa 1592 数据库

时间:2018-09-15 11:01:48      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:count()   mes   ret   algorithm   namespace   set   code   return   直接   

题目

给出一个表格,问有没有r1、r2、c1、c2满足着两行与两列相交的单元格内部分别相同。

题解

#include <iostream>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;

const int COL = 10 + 5;
const int ROW = 10000 + 15;
int n, m;

vector<string> Strcache;
map<string, int> IDcache;
vector<int> DATA[ROW];
map<pair<int, int>, int> comp;

int ID_alloc(string str)     //string转ID,存vec数组
{
    if (IDcache.count(str))  return IDcache[str];
    Strcache.push_back(str);
    return IDcache[str] = Strcache.size() - 1;
}

void Read()
{
    string str;
    char temp = cin.get();       //注意
    for (int i = 0; i < n; ++i) {
        while (true) {
            temp = cin.get();
            if (temp == '\n' || temp == '\r') {
                if (!str.empty())     DATA[i].push_back(ID_alloc(str));
                str.clear();
                break;
            }
            else if (temp == ',') {
                DATA[i].push_back(ID_alloc(str));
                str.clear();
            }
            else   str += temp;
        }
    }
}

void Solve()
{
    int x, y, c1, c2;
    for (c1 = 0; c1 < m; ++c1) {
        for (c2 = c1 + 1; c2 < m; ++c2) {
            comp.clear();
            for (int r = 0; r < n; ++r) {
                x = DATA[r][c1]; y = DATA[r][c2];
                pair<int, int> p = make_pair(x, y);
                if (!comp.count(p))   comp[p] = r;
                else {
                    cout << "NO" << endl;
                    cout << comp[p] + 1 << " " << r + 1 << endl << c1 + 1 << " " << c2 + 1 << endl;
                    return;
                }
            }
        }
    }
    cout << "YES" << endl;
}
int main()
{
    while (cin >> n >> m){
        Read();
        Solve();
        for (int i = 0; i<n; i++) DATA[i].clear();
            IDcache.clear(); Strcache.clear();
    }
    return 0;
}

总结

  1. string直接比较,会效率低 ——> 给每个string分配ID(相同string分配同一ID) 变成vec数组(相当于二维),表格中各string变成一个ID
  2. 四重循环比较会低效 ——> 循环列(c1, c2两重循环),然后在比较行时用一个pair<int, int>到int的map,存储对应r1, r2数据映射到该行r,再对比pair,输出r
  3. 用cin.get()注意考虑之前的换行,会运行报错
  4. string,vec之类循环时候记得clear
  5. count()返回count括号里面的对象数目

UVa 1592 数据库

标签:count()   mes   ret   algorithm   namespace   set   code   return   直接   

原文地址:https://www.cnblogs.com/TuerLueur/p/9650225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!