結果

問題 No.1612 I hate Construct a Palindrome
ユーザー 👑 Nachia
提出日時 2021-07-21 21:56:07
言語 C++17(gcc12)
(gcc 12.3.0 + boost 1.87.0)
結果
TLE  
実行時間 -
コード長 2,244 bytes
コンパイル時間 4,201 ms
コンパイル使用メモリ 125,268 KB
最終ジャッジ日時 2025-01-23 04:02:53
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 30 TLE * 1 MLE * 5
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
using ll = long long;
using ull = unsigned long long;
#define rep(i,n) for(int i=0; i<(n); i++) 

struct Edge2{ int u,v; char c; };
struct Edge{ int to; char c; int i; };
struct PathInfo{
  string s; vector<int> e;
  PathInfo& operator+=(const PathInfo& r){
    s += r.s;
    for(auto i : r.e) e.push_back(i);
    return *this;
  }
};

int N,M;
vector<vector<Edge>> E;
vector<Edge2> J;
vector<vector<int>> Ch;

PathInfo getPath(int s,int t){
  vector<int> I = {s};
  vector<int> P(N,-1);
  vector<int> Pc(N,-1);
  vector<int> Pi(N,-1);
  vector<int> F(N,0);
  F[0] = 1;
  rep(i,I.size()){
    int p = I[i];
    for(auto e : E[p]) if(F[e.to] == 0){
      F[e.to] = 1;
      I.push_back(e.to);
      Pc[e.to] = e.c;
      Pi[e.to] = e.i;
      P[e.to] = p;
    }
  }
  string ans;
  vector<int> ansi;
  while(t != s){
    ans.push_back(Pc[t]);
    ansi.push_back(Pi[t]);
    t = P[t];
  }
  reverse(ans.begin(),ans.end());
  reverse(ansi.begin(),ansi.end());
  return { move(ans),move(ansi) };
}

bool iskaibun(const string& s){
  rep(i,s.size()) if(s[i] != s[s.size()-1-i]) return false;
  return true;
}

int main(){
  cin >> N >> M;
  E.resize(N);
  Ch.resize(26);
  rep(i,M){
    int u,v; char c; cin >> u >> v >> c; u--; v--;
    E[u].push_back({v,c,i});
    E[v].push_back({u,c,i});
    Ch[c-'a'].push_back(i);
    J.push_back({u,v,c});
  }

  Edge firstE = E[N-1][0];
  int needE = -1;
  rep(c,26) if(firstE.c-'a' != c) if(Ch[c].size()){ needE = Ch[c][0]; }
  if(needE == -1){ cout << "-1\n"; return 0; }

  auto ans1 = getPath(0,J[needE].u);
  ans1 += PathInfo{string(1,J[needE].c),{needE}};
  ans1 += getPath(J[needE].v,N-1);
  auto ans2 = getPath(0,J[needE].v);
  ans2 += PathInfo{string(1,J[needE].c),{needE}};
  ans2 += getPath(J[needE].u,N-1);
  
  if(ans1.s.size() > ans2.s.size()) swap(ans1,ans2);

  if(iskaibun(ans1.s)){
    ans1.s += string(2,firstE.c);
    rep(c,2) ans1.e.push_back(firstE.i);
  }

  cout << ans1.e.size() << "\n";
  for(auto a : ans1.e) cout << (a+1) << "\n";

  return 0;
}

struct ios_do_not_sync{
  ios_do_not_sync(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
  }
} ios_do_not_sync_instance;


0