構造思維 Codeforces Round #644 (Div. 3) F. Spy-string

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.

題目大意:
給你n個長爲m的字符串,構造一個字符串s,這個字符串長度爲m,並且與給的n個字符串分別最多相差一個字符;


幾乎告訴你是構造題,但是怎麼構造呢?

直接改動第一個字符串的一個字母,因爲要保證每個字符串都符合條件,所以第一個字符串也要符合,既然它要符合,那麼就以它改動一個字母后的字符串作爲答案判斷就行;

代碼:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=1100;
const int M=2000000;
const LL mod=1e9+7;
string s[20];
int n,m;
bool judge(string p){
	for(int i=1;i<=n;i++){
		int sum=0;
		for(int j=0;j<m;j++){
			if(s[i][j]!=p[j]) sum++;
		}
		if(sum>=2) return false;
	}
	return true;
}
int main(){
	int t;cin>>t;
	while(t--){
		cin>>n>>m;
		for(int i=1;i<=n;i++) cin>>s[i];
		int ok=0;
		for(int i=0;i<m;i++){
			if(ok) break;
			for(int j=0;j<=25;j++){
				string t=s[1];
				t[i]='a'+j;
				if(judge(t)){
					ok=1;
					cout<<t<<endl;
					break;
				}
			}
		}
		if(!ok) cout<<-1<<endl; 
	}
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章