codeforces1360F

https://codeforces.com/problemset/problem/1360/F

题意:

n个长度为m的字符串,求字符串s使得和每个给定的字符串最多只有一个位置不同,如果没有输出-1

思路:

数据范围只有10,可以使用位运算求解,首先通过第一个字符串可以确定m-1个位置,有一个位置可以更改,然后和剩下的字符串进行比较,保证最多只有一个位置不同即可

题解:

#include <iostream>
#include <cstring>
#include <algorithm>
#define eb emplace_back
#define divUp(a,b) (a+b-1)/b
#define mkp(x,y) make_pair(x,y)
#define all(v) begin(v),end(v)
#define int long long
using namespace std;
typedef unsigned long long ull;
typedef pair<int, int> pii;
bool checkP2(int n)
{
    return n > 0 and (n & (n - 1)) == 0;
};
string a[20];
int cnt[1 << 12];
void init()
{
    for (int i = 0; i < 1 << 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            cnt[i] += i >> j & 1;
        }
    }
}
bool check(string &s, string &t, int p)
{
    int cnt = 0;
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] != t[i]) cnt++;
    }
    if (cnt <= 1) return true;
    else if (cnt == 2) {
        if (s[p] == '*') {
            s[p] = t[p];
            return true;
        } else return false;
    }
    return false;
}
void solve()
{
    int n;
    cin >> n;
    int m;
    cin >> m;
    for (int = 1; i <= n; i++) cin >> a[i];
    string s = "";
    for (int i = 0; i < 1 << m; i++)
    {
        if (cnt[i] == m - 1)
        {   s = "";
            bool ok = true;
            int p = -1;
            for (int j = 0; j < m; j++)
            {
                if (i >> j & 1)
                {
                    s += a[1][j];
                }
                else s += '*', p = j;
            }
            for (int j = 2; j <= n; j++)
            {
                if (!check(s, a[j], p))
                {
                    ok = false;
                    break;
                }
            }
            if (ok) {
                if (s[p] == '*') s = a[1];
                cout << s << endl;
                return;
            }
        }
    }
    cout << -1 << endl;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int _;
    cin >> _;
    while (_--)
        solve();
    return 0;
}
posted @ 2021-10-12 15:50  指引盗寇入太行  阅读(31)  评论(0编辑  收藏  举报