• UVa 1592 数据库


    题目

    给出一个表格,问有没有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 == '
    ' || temp == '
    ') {
                    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括号里面的对象数目
    醉 生 梦 死
  • 相关阅读:
    居敬持志
    测试内容
    TestMarkDown
    git
    面试题
    兼容的可视区高度和宽度
    JS(数据类型、预解析、闭包、作用域、this)
    JavaScript new 一个构造函数
    Windows下gm打水印老是报gm convert: Unable to read font (n019003l.pfb)问题
    如何开始一个vue+webpack项目
  • 原文地址:https://www.cnblogs.com/TuerLueur/p/9650225.html
Copyright © 2020-2023  润新知