感觉T2反而是最难的。。反正代码是越来越暴力了。。。
这次前两题的代码都很没美感。。
不过T1终于上240了,T2终于上400了(然而是550啊)
T3调了半天结果竟然是数组开小了= =
T1 PalindromePrime
丑陋的暴力
#include <bits/stdc++.h>
using namespace std;
class PalindromePrime {
public:
int count( int L, int R );
};
int pd(int x){
if (x==1) return 0;
for(int i=2;i*i<=x;i++)
if (x%i==0) return 0;
return 1;
}
int ppd(int x){
if (x<10) return 1;
if (x<100) return x/10==x%10;
if (x<1000) return x/100==x%10;
return 0;
}
int PalindromePrime::count(int L, int R) {
int ans=0;
for(int i=L;i<=R;i++)
if (pd(i)&&ppd(i)) ans++;
return ans;
}
T2 FourStrings
丑陋的暴力
#include <bits/stdc++.h>
using namespace std;
string cc[4];
int s[4];
class FourStrings {
public:
int shortestLength( string a, string b, string c, string d );
};
int pd(int i,int x,int y){
int p1=i,p2=0;
while(p1<s[x]&&p2<s[y]){
if (cc[x][p1]!=cc[y][p2]) return 0;
p1++;p2++;
}
return 1;
}
int pj(int x,int y){
for(int i=0;i<s[x];i++)
if (pd(i,x,y)) return max(0,s[y]-(s[x]-i));
return s[y];
}
int www(int i,int j,int k,int l){
int w=i,sum=s[i];
int v=pj(w,j);
if (v) w=j;
sum+=v;
v=pj(w,k);
if (v) w=k;
sum+=v;
v=pj(w,l);
sum+=v;
return sum;
}
int FourStrings::shortestLength(string a, string b, string c, string d) {
cc[0]=a;cc[1]=b;cc[2]=c;cc[3]=d;
for(int i=0;i<4;i++) s[i]=cc[i].size();
int ans=s[1]+s[2]+s[3]+s[0];
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if (j!=i)
for(int k=0;k<4;k++)
if (k!=i&&k!=j){
int l=6-i-j-k;
ans=min(ans,www(i,j,k,l));
}
return ans;
}
T3 PalindromePath
f[i][j] f [ i ] [ j ] 表示 0 0 到的路径与 1 1 到的路径相同时的最短路,然后跑下SPFA就行,不过好像这题bfs也一样。
#include <bits/stdc++.h>
using namespace std;
const int N=21;
const int M=401;
const int INF=2e9;
int f[N][N],cnt,head[N],Next[M],v[M],w[M],b[N][N];
struct data{
int x,y;
};
queue<data> h;
class PalindromePath {
public:
int shortestLength( int n, vector <int> a, vector <int> b, string c );
};
void add(int x,int y,char z){
Next[++cnt]=head[x];
head[x]=cnt;
v[cnt]=y;
w[cnt]=z;
}
void spfa(){
while(!h.empty()) h.pop();
h.push((data){0,1});
b[0][1]=1;
while(!h.empty()){
data q=h.front();
h.pop();
int x=q.x,y=q.y;
b[x][y]=0;
for(int i=head[x];i!=-1;i=Next[i])
for(int j=head[y];j!=-1;j=Next[j])
if (w[i]==w[j]&&f[x][y]+2<f[v[i]][v[j]]){
f[v[i]][v[j]]=f[x][y]+2;
if (!b[v[i]][v[j]]){
b[v[i]][v[j]]=1;
h.push((data){v[i],v[j]});
}
}
}
}
int PalindromePath::shortestLength(int n, vector <int> a, vector <int> b, string c) {
memset(f,0x3f,sizeof f);
memset(head,-1,sizeof head);
f[0][1]=0;cnt=0;
for(int i=0;i<a.size();i++){
add(a[i],b[i],c[i]);
add(b[i],a[i],c[i]);
}
spfa();
int ans=INF;
for(int i=0;i<n;i++) ans=min(ans,f[i][i]);
cout<<ans<<endl;
for(int i=0;i<n;i++)
for(int j=head[i];j!=-1;j=Next[j])
ans=min(ans,f[i][v[j]]+1),cout<<f[i][v[j]]<<' ';
if (ans>1e9) ans=-1;
return ans;
}