結果
| 問題 |
No.1194 Replace
|
| コンテスト | |
| ユーザー |
snow39
|
| 提出日時 | 2020-08-22 15:27:37 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 810 ms / 2,000 ms |
| コード長 | 2,574 bytes |
| コンパイル時間 | 1,504 ms |
| コンパイル使用メモリ | 119,808 KB |
| 実行使用メモリ | 103,236 KB |
| 最終ジャッジ日時 | 2024-10-15 09:42:00 |
| 合計ジャッジ時間 | 15,103 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 27 |
ソースコード
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#include <tuple>
#define mkp make_pair
#define mkt make_tuple
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define all(v) v.begin(),v.end()
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
template<class T> void chmin(T &a,const T &b){if(a>b) a=b;}
template<class T> void chmax(T &a,const T &b){if(a<b) a=b;}
/* example
int n=scc.scc();
scc.build(n,g);
(g:outside)
*/
struct StronglyConnectedComponents{
vector<int> used,cmp,vs;
vector<vector<int>> ori;
vector<vector<int>> v,rv;
StronglyConnectedComponents(int n):used(n),cmp(n,-1),v(n),rv(n){}
void add_edge(int x,int y){
v[x].push_back(y);
rv[y].push_back(x);
}
void dfs(int x){
used[x]=true;
for(auto to:v[x]) if(!used[to]) dfs(to);
vs.push_back(x);
}
void rdfs(int x,int k){
cmp[x]=k;
for(auto to:rv[x]) if(cmp[to]==-1) rdfs(to,k);
}
int scc(){
for(int i=0;i<used.size();i++) if(!used[i]) dfs(i);
reverse(vs.begin(),vs.end());
int k=0;
for(auto x:vs) if(cmp[x]==-1) rdfs(x,k++);
ori.resize(k);
for(int i=0;i<used.size();i++) ori[cmp[i]].push_back(i);
return k;//k:size
}
void build(int k,vector<vector<int>> &g){
g.resize(k);
for(int i=0;i<v.size();i++){
for(auto to:v[i]){
int x=cmp[i],y=cmp[to];
if(x!=y) g[x].push_back(y);
}
}
}
};
vector<vector<int>> g;
vector<int> vis;
vector<int> dp;
vector<ll> B,C;
void dfs(int now){
if(vis[now]) return;
for(auto nex:g[now]){
dfs(nex);
chmax(dp[now],dp[nex]);
}
vis[now]=1;
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
ll N,M;
cin>>N>>M;
B.resize(M);
C.resize(M);
rep(i,M) cin>>B[i]>>C[i];
vector<int> v;
rep(i,M) v.push_back(B[i]);
rep(i,M) v.push_back(C[i]);
sort(all(v));
v.erase(unique(all(v)),v.end());
int V=v.size();
map<int,int> mp;
rep(i,V) mp[v[i]]=i;
StronglyConnectedComponents scc(V);
rep(i,M){
scc.add_edge(mp[B[i]],mp[C[i]]);
}
int S=scc.scc();
scc.build(S,g);
dp.resize(S,0);
for(int i=0;i<V;i++) chmax(dp[scc.cmp[i]],v[i]);
vis.resize(S,0);
for(int i=0;i<S;i++){
if(vis[i]) continue;
dfs(i);
}
ll ans=N*(N+1)/2;
for(int i=0;i<V;i++){
ans-=v[i];
ans+=dp[scc.cmp[i]];
}
cout<<ans<<endl;
return 0;
}
snow39