#644 (Div. 3)F. Spy-string(暴力枚舉)

題目描述

You are given n strings a1,a2,…,an: all of them have the same length m. The strings consist of lowercase English letters.
Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string ai, there is no more than one position j such that ai[j]≠s[j].
Note that the desired string s may be equal to one of the given strings ai, or it may differ from all the given strings.
For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.

Input

The first line contains an integer t (1≤t≤100) — the number of test cases. Then t test cases follow.
Each test case starts with a line containing two positive integers n (1≤n≤10) and m (1≤m≤10) — the number of strings and their length.
Then follow n strings ai, one per line. Each of them has length m and consists of lowercase English letters.

Output

Print t answers to the test cases. Each answer (if it exists) is a string of length m consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print “-1” (“minus one”, without quotes).

Example

input
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
output
abab
-1
aaa
ab
z

Note

The first test case was explained in the statement.
In the second test case, the answer does not exist.

題目大意

給你n個字符串,每個字符串長度爲m,要求是否存在一個字符串使得該字符串與每個字符串的不同的字符個數小於等於1個。

題目分析

這道題就是暴力枚舉每一種情況,然後驗證是否合法即可。
其實就是考察寫代碼的能力。(比賽的時候我看出來是要暴力做了,但就是寫不出來。。。)

代碼如下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <map>
#include <unordered_map>
#include <queue>
#include <vector>
#include <set> 
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
int const N=105;
int n,m;
string ans,s[15];
bool check()     //檢查該情況是否合法
{
    for(int i=2;i<=m;i++)   //枚舉其它m-1個字符串
    {
        int k=0;
        for(int j=0;j<n;j++)
        {
            if(ans[j]!=s[i][j]) k++;   //統計不相同的字母數量
            if(k>=2) return false;     //大於2則不合法
        }
    }
    return true;    //否則合法
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		cin>>m>>n;
		for(int i=1;i<=m;i++)
			cin>>s[i];
		
		bool st=false;
		for(int i=0;i<n;i++) //枚舉每一位
		{
		    ans=s[1];       //重置ans,保證每次只修改一個位置
		    for(char j='a';j<='z';j++)   //枚舉每一個字母
		    {
		        ans[i]=j;
		        if(check()) {st=true; break;}  //檢查是否合法,合法即可輸出
		    }
		    if(st) break;
		}
		if(st) cout<<ans<<endl;   //如果有合法情況則輸出
		else puts("-1");          //沒有輸出-1
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章