text
stringlengths
49
983k
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef complex<double> P; typedef pair<int,int> pii; #define REP(i,n) for(ll i=0;i<n;++i) #define REPR(i,n) for(ll i=1;i<n;++i) #define FOR(i,a,b) for(ll i=a;i<b;++i) #define DEBUG(x) cout<<#x<<": "<<x<<endl #define DEBUG_VEC(v) cout<<#v<<":";REP(i,v.size())cout<<" "<<v[i];cout<<endl #define ALL(a) (a).begin(),(a).end() #define MOD (ll)(1e9+7) #define ADD(a,b) a=((a)+(b))%MOD #define FIX(a) ((a)%MOD+MOD)%MOD static const ll INF = 1000000000000000ll; #define MAX_V 1000 // Dinic http://www.prefield.com/algorithm/graph/dinic.html struct dinic{ struct edge{int to;ll cost;}; int n; vector< vector<edge> > G; vector<vl> flow, capacity; #define RESIDUE(s,t) (capacity[s][t]-flow[s][t]) vi level; vector<bool> finished; dinic(int _n){ n = _n; G.assign(n,vector<edge>()); flow.assign(n,vl(n,0)); capacity.assign(n,vl(n,0)); level.assign(n,0); finished.assign(n,false); } void add_edge(int from,int to,ll cost){ assert(0<=from && from<n); assert(0<=to && to<n); G[from].push_back((edge){to,cost}); G[to].push_back((edge){from,0ll}); // ????????????????????????????????????????????? } ll dfs(int u, int t, ll cur){ if(u==t || cur==0) return cur; if(finished[u]) return 0; finished[u] = true; REP(i,G[u].size()){ edge e = G[u][i]; if(level[e.to] > level[u]){ ll f = dfs(e.to, t, min(cur, RESIDUE(u,e.to))); if(f>0){ flow[u][e.to] += f; flow[e.to][u] -= f; finished[u] = false; return f; } } } return 0; } ll calc(int s, int t){ REP(i,n)REP(j,n)flow[i][j]=capacity[i][j]=0; REP(u,n)REP(j,G[u].size()){ edge e = G[u][j]; capacity[u][e.to] += e.cost; } ll total = 0; while(true){ REP(i,n)level[i] = -1; level[s] = 0; queue<int> Q; Q.push(s); int d = n; while(!Q.empty()){ int u = Q.front(); Q.pop(); REP(i,G[u].size()){ edge e = G[u][i]; if(RESIDUE(u,e.to) > 0 && level[e.to] == -1){ Q.push(e.to); level[e.to] = level[u] + 1; } } } REP(i,n)finished[i]=false; bool flag = false; while(true){ ll f = dfs(s,t,INF); if(f==0)break; total += f; flag = true; } if(!flag)break; } return total; } }; int main(){ map<string,int> mp; mp["Monday"] = 0; mp["Tuesday"] = 1; mp["Wednesday"] = 2; mp["Thursday"] = 3; mp["Friday"] = 4; mp["Saturday"] = 5; mp["Sunday"] = 6; while(true){ int n; ll w; cin>>n>>w; if(!n)break; dinic D(1+7+n+1); int src = n; int dst = n+1; int week[7]; REP(i,7){ week[i] = n+2+i; D.add_edge(src,week[i],w); } ll sum = 0; REP(i,n){ ll t; int c; cin>>t>>c; sum += t; while(c--){ string s; cin>>s; assert(mp.count(s)==1); int d = mp[s]; D.add_edge(week[d],i,INF); } D.add_edge(i,dst,t); } ll flow = D.calc(src,dst); if(flow==sum){ cout<<"Yes"<<endl; }else{ cout<<"No"<<endl; } } return 0; }
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; //#define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define BIG_NUM 999999999999999 #define NUM 3000 //辺を表す構造体(行先、容量、逆辺のインデックス) struct Edge{ Edge(int arg_to,ll arg_capacity,int arg_rev_index){ to = arg_to; capacity = arg_capacity; rev_index = arg_rev_index; } int to,rev_index; ll capacity; }; int V,E; int N; ll W; vector<Edge> G[NUM]; //グラフの隣接リスト表現 ll dist[NUM]; //sourceからの距離 int cheked_index[NUM]; //どこまで調べ終わったか //fromからtoへ向かう容量capacityの辺をグラフに追加する void add_edge(int from,int to,ll capacity){ G[from].push_back(Edge(to,capacity,G[to].size())); G[to].push_back(Edge(from,0,G[from].size()-1)); //逆辺の、初期容量は0 } //sourceからの最短距離をBFSで計算する void bfs(int source){ for(int i = 0; i < V; i++)dist[i] = -1; queue<int> Q; dist[source] = 0; Q.push(source); while(!Q.empty()){ int node_id = Q.front(); Q.pop(); for(int i = 0; i < G[node_id].size(); i++){ Edge &e = G[node_id][i]; if(e.capacity > 0 && dist[e.to] < 0){ //辺の容量が正で、かつエッジの行先に未訪問の場合 dist[e.to] = dist[node_id]+1; Q.push(e.to); } } } } //増加パスをDFSで探す ll dfs(int node_id,int sink,ll flow){ if(node_id == sink)return flow; //終点についたらflowをreturn for(int &i = cheked_index[node_id]; i < G[node_id].size(); i++){ //node_idから出ているエッジを調査 Edge &e = G[node_id][i]; if(e.capacity > 0 && dist[node_id] < dist[e.to]){ //流せる余裕があり、かつsourceからの距離が増加する方法である場合 ll tmp_flow = dfs(e.to,sink,min(flow,e.capacity)); //流せるだけ流す if(tmp_flow > 0){ //流せた場合 e.capacity -= tmp_flow; //流した分、エッジの容量を削減する G[e.to][e.rev_index].capacity += tmp_flow; //逆辺の容量を、流した分だけ増加させる return tmp_flow; } } } return 0; } //sourceからsinkへの最大流を求める ll max_flow(int source,int sink){ //source:始点 sink:終点 ll flow = 0,add; while(true){ //増加パスが存在する限り、流量を追加し続ける bfs(source); if(dist[sink] < 0)break; //sourceからsinkへと辿り着く残余グラフがない、つまり増加パスが無くなった場合、break for(int i = 0; i < V; i++)cheked_index[i] = 0; while((add = dfs(source,sink,BIG_NUM)) > 0){ //増加パスが見つかる間、加算 flow += add; } } return flow; } void func(){ for(int i = 0; i < NUM; i++)G[i].clear(); int source = 0,sink = 1; //月~日に、容量Wの辺を張る for(int node_id = 2; node_id <= 8; node_id++){ add_edge(source,node_id,W); } int index = 9; ll total_need = 0,need_num; int num; char buf[20]; for(int loop = 0; loop < N; loop++){ scanf("%lld %d",&need_num,&num); add_edge(index,sink,need_num); //生徒からsinkへ容量need_numの辺を張る total_need += need_num; for(int i = 0; i < num; i++){ scanf("%s",buf); switch(buf[0]){ //都合の良い曜日から、生徒へ容量Wの辺を張る case 'M': add_edge(2,index,W); break; case 'T': if(buf[1] == 'u'){ add_edge(3,index,W); }else{ add_edge(5,index,W); } break; case 'W': add_edge(4,index,W); break; case 'F': add_edge(6,index,W); break; case 'S': if(buf[1] == 'a'){ add_edge(7,index,W); }else{ add_edge(8,index,W); } break; } } index++; } V = index; if(total_need == max_flow(source,sink)){ printf("Yes\n"); }else{ printf("No\n"); } } int main(){ while(true){ scanf("%d %lld",&N,&W); if(N == 0 && W == 0)break; func(); } return 0; }
#include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; typedef long long lli; typedef lli Weight; const lli INF=1LL<<60; const int MAX_V=500; int V; int N;lli W; string name[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; #define REP(i,x)for(int i=0;i<(int)x;i++) struct Edge{ int src,dst; Weight weight; int rev; Edge(int f, int t, Weight c,int rev=0):src(f),dst(t),weight(c),rev(rev){} }; struct Node:public vector<Edge>{ //頂点の情報を記録する場合 }; bool operator<(const Edge &a,const Edge &b){ return a.weight<b.weight; } bool operator>(const Edge &a,const Edge &b){return b<a;} typedef vector<Node> Graph; typedef vector<vector<Weight> > Matrix; void add_edge(Graph &G,int s,int t,Weight cap){ G[s].push_back(Edge(s,t,cap,G[t].size())); G[t].push_back(Edge(t,s,0,G[s].size()-1)); } void bfs(const Graph &G,vector<int> &level,int s){ level[s]=0; queue<int> que; que.push(s); while(!que.empty()){ int v=que.front();que.pop(); REP(i,G[v].size()){ const Edge &e=G[v][i]; if(e.weight>0 && level[e.dst] < 0){ level[e.dst] = level[v] +1; que.push(e.dst); } } } } Weight dfs(Graph &G,vector<int> &level,vector<int> &iter,int v,int t,Weight flow){ if(v==t)return flow; for(int &i=iter[v];i<(int)G[v].size();i++){ Edge &e=G[v][i]; if(e.weight>0&&level[v]<level[e.dst]){ Weight d=dfs(G,level,iter,e.dst,t,min(flow,e.weight)); if(d>0){ e.weight-=d; G[e.dst][e.rev].weight+=d; return d; } } } return 0; } // Weight max_flow(Graph &G,int s,int t){ Weight flow = 0; while(true){ vector<int> level(G.size(),-1); vector<int> iter(G.size(),0); bfs(G,level,s); if(level[t]<0)break; // もう流せない Weight f=0; while((f=dfs(G,level,iter,s,t,INF))>0){ flow+=f; } } return flow; } inline int string2int(const string &a){ return find(name,name+7,a)-name; } int main() { while(cin>>N>>W){ Graph G(N+9); if(N==0)break; int s=N+7; int e=N+7+1; lli req=0; V=N+7+2; for(int i=0;i<N;i++){ lli c,t; cin>>t>>c; add_edge(G,s,i,t); req+=t; for(int j=0;j<c;j++){ string k; cin>>k; add_edge(G,i,string2int(k)+N,t); } } for(int i=0;i<7;i++){ add_edge(G,N+i,e,W); } lli flow=max_flow(G,s,e); if(flow==req){ cout<<"Yes"<<endl;; }else{ cout<<"No"<<endl; } } return 0; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct edge{ int to; long long cap; int rev; }; vector<vector<edge> > G; bool used[109]; void add_edge(int from,int to,long long cap){ G[from].push_back({to,cap,(int)G[to].size()}); G[to].push_back({from,0,(int)G[from].size()-1}); } long long dfs(int v,int t,long long f){ if(v==t)return f; used[v]=true; for(int i=0;i<G[v].size();i++){ edge &e=G[v][i]; if(!used[e.to]&&e.cap>0){ long long d=dfs(e.to,t,min(f,e.cap)); if(d>0){ e.cap-=d; G[e.to][e.rev].cap+=d; return d; } } } return 0; } long long max_flow(int s,int t){ long long flow=0; for(;;){ fill(begin(used),end(used),false); long long f=dfs(s,t,1LL<<62); if(f==0)return flow; flow+=f; } } int main(){ for(long long N,W;cin>>N>>W,N;){ G=vector<vector<edge> >(109); for(int i=0;i<7;i++){ add_edge(107,100+i,W); } long long tsum=0; for(int i=0;i<N;i++){ long long t,c; cin>>t>>c; tsum+=t; while(c--){ char dow[99]; cin>>dow; add_edge(100+( (dow[0]=='S')?(dow[1]=='u')?0:1: (dow[0]=='M')?2: (dow[0]=='T')?(dow[1]=='u')?3:4: (dow[0]=='W')?5:6),i,1LL<<62); } add_edge(i,108,t); } cout<<((max_flow(107,108)==tsum)?"Yes":"No")<<endl; } }
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<cmath> #include<cstring> #include<queue> #include<cstdio> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) #define pb push_back #define mp make_pair #define all(in) in.begin(),in.end() const double PI=acos(-1); const double EPS=1e-10; const int inf=1e9; using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pii; struct edge { ll to, cap, rev; };//ikisaki youryou gyakuhen #define MAX 200 vector<vector<edge> >G(MAX);//[MAX]; vector<bool>used(MAX);//[MAX]; void add_edge(ll from, ll to, ll cap){ edge q={to,cap,ll(G[to].size())}; G[from].push_back(q); q={from,0,ll(G[from].size()-1)}; G[to].push_back(q); } ll dfs(ll v, ll t, ll f) { if(v == t) return f; used[v] = 1; for(int i = 0 ; i < G[v].size(); i++){ edge &e = G[v][i]; if(used[e.to] || e.cap <= 0) continue; ll d = dfs(e.to, t, min(f, e.cap)); if(d > 0){ e.cap -= d; G[e.to][e.rev].cap += d; return d; } } return 0; } ll ford_fulkerson(ll s, ll t) {//from s to t ll flow = 0, f; while(1){ used=vector<bool>(MAX,false); f = dfs(s, t, inf); if(f == 0) return flow; flow += f; } } int gcd(int a,int b){ if(a<b)swap(a,b); if(b==0)return a; return gcd(b,a%b); } int main(){ ll n,m; map<string,int>ma; ma["Sunday"]=0; ma["Monday"]=1; ma["Tuesday"]=2; ma["Wednesday"]=3; ma["Thursday"]=4; ma["Friday"]=5; ma["Saturday"]=6; while(cin>>n>>m,n+m){ rep(i,MAX)G[i].clear(); ll s=n+7,t=s+1; ll out=0; rep(i,n){ ll c,d; cin>>c>>d; out+=c; add_edge(s,i,c); rep(j,d){ string ss; cin>>ss; add_edge(i,n+ma[ss],m); } } rep(i,7)add_edge(n+i,t,m); if(ford_fulkerson(s,t)==out)cout<<"Yes"<<endl; else cout<<"No"<<endl; } }
#include <iostream> #include <vector> #include <map> #include <cstring> #include <climits> using namespace std; typedef long long ll; #define MAX_V 1000 ll cap[MAX_V][MAX_V]; bool used[MAX_V]; ll n; ll dfs(ll v, ll t, ll f){ if(v==t) return f; used[v] = true; for(ll i = 0; i < n; i++){ ll c = cap[v][i]; if(!used[i] && c > 0){ ll d = dfs(i , t , min(f, c)); if(d > 0){ cap[v][i] -= d; cap[i][v] += d; return d; } } } return 0; } ll mf(ll s, ll t){ ll flow = 0; for(;;){ memset(used , 0 , sizeof(used)); ll f = dfs(s,t,100000000000LL); if(f == 0) return flow; flow += f; } } void add_edge(ll from, ll to, ll c){ cap[from][to] = c; cap[to][from] = 0; } int main(){ ll w; map<string,int> week; week["Sunday"] = 0; week["Monday"] = 1; week["Tuesday"] = 2; week["Wednesday"] = 3; week["Thursday"] = 4; week["Friday"] = 5; week["Saturday"] = 6; while(cin >> n >> w, n || w){ memset(cap, -1, sizeof(cap)); for(ll i = 0; i < 7; i++){ add_edge(0, i + 1, w); } ll sum = 0; for(ll i = 0; i < n; i++){ ll tn, cn; cin >> tn >> cn; add_edge(i + 8, n + 8, tn); sum += tn; for(ll j = 0; j < cn; j++){ string s; cin >> s; ll from = week[s] + 1; add_edge(from, i + 8, w); } } n = n + 9; ll flow = mf(0, n - 1); if(flow == sum){ cout << "Yes" << endl; } else{ cout << "No" << endl; } } }
#include <iostream> #include <vector> #include <map> #include <cstring> #include <climits> using namespace std; typedef long long ll; class Edge{ public: ll to, cap, rev; Edge(){} Edge(ll to, ll cap, ll rev) : to(to), cap(cap), rev(rev) {} }; vector<Edge> G[1000]; bool used[1000]; void add_edge(ll from, ll to, ll cap){ G[from].push_back(Edge(to, cap, G[to].size())); G[to].push_back(Edge(from, 0, G[from].size() - 1)); } ll dfs(ll v, ll t, ll f){ if(v == t) return f; used[v] = true; for(ll i = 0; i < G[v].size(); i++){ Edge &e = G[v][i]; if(!used[e.to] && e.cap > 0){ ll d = dfs(e.to, t, min(f, e.cap)); if(d > 0){ e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } ll max_flow(ll s, ll t){ ll flow = 0; while(true){ memset(used, 0, sizeof(used)); ll f = dfs(s, t, LONG_LONG_MAX); if(f == 0) return flow; flow += f; } } int main(){ ll n, w; map<string,int> week; week["Sunday"] = 0; week["Monday"] = 1; week["Tuesday"] = 2; week["Wednesday"] = 3; week["Thursday"] = 4; week["Friday"] = 5; week["Saturday"] = 6; while(cin >> n >> w, n || w){ for(ll i = 0; i < 1000; i++){ G[i].clear(); } for(ll i = 0; i < 7; i++){ add_edge(0, i + 1, w); } ll sum = 0; for(ll i = 0; i < n; i++){ ll tn, cn; cin >> tn >> cn; add_edge(i + 8, n + 8, tn); sum += tn; for(ll j = 0; j < cn; j++){ string s; cin >> s; ll from = week[s] + 1; add_edge(from, i + 8, w); } } ll flow = max_flow(0, n + 8); if(flow == sum){ cout << "Yes" << endl; } else{ cout << "No" << endl; } } }
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #include<utility> #include<complex> #include<functional> using namespace std; /* constant */ const int MAX_N = 100; const int MAX_GN = MAX_N + 9; const long long LLINF = 1LL << 62; const string wdnames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; /* typedef */ typedef long long ll; struct Edge { int ui, vi; ll c; Edge(int _ui, int _vi, ll _c): ui(_ui), vi(_vi), c(_c) {} }; typedef vector<Edge> ve; /* global variables */ int n, gn, st, gl; ll w, sumti; map<string,int> wdnhash; ve nbrs[MAX_GN]; ll minfs[MAX_GN], flows[MAX_GN][MAX_GN]; int prvs[MAX_GN]; /* subroutines */ /* main */ int main() { for (int i = 0; i < 7; i++) wdnhash[wdnames[i]] = i; for (;;) { cin >> n >> w; if (n == 0) break; gn = n + 9; st = n + 7; gl = n + 8; for (int i = 0; i < gn; i++) nbrs[i].clear(); sumti = 0; for (int i = 0; i < n; i++) { ll ti; int ci; cin >> ti >> ci; sumti += ti; nbrs[st].push_back(Edge(st, i, ti)); for (int j = 0; j < ci; j++) { string wdname; cin >> wdname; int wj = n + wdnhash[wdname]; nbrs[i].push_back(Edge(i, wj, LLINF)); nbrs[wj].push_back(Edge(wj, i, 0)); } } for (int i = 0; i < 7; i++) nbrs[n + i].push_back(Edge(n + i, gl, w)); memset(flows, 0, sizeof(flows)); ll max_flow = 0; for (;;) { //printf("max_flow = %lld\n", max_flow); memset(prvs, -1, sizeof(prvs)); prvs[st] = st; minfs[st] = LLINF; queue<int> q; q.push(st); while (! q.empty()) { int ui = q.front(); q.pop(); if (ui == gl) break; ve& nbru = nbrs[ui]; for (ve::iterator vit = nbru.begin(); vit != nbru.end(); vit++) { int vi = vit->vi; ll vc = vit->c - flows[ui][vi]; if (prvs[vi] < 0 && vc > 0) { prvs[vi] = ui; minfs[vi] = (minfs[ui] < vc) ? minfs[ui] : vc; q.push(vi); } } } if (prvs[gl] < 0) break; ll min_flow = minfs[gl]; for (int j = gl; j != st;) { int i = prvs[j]; flows[i][j] += min_flow; flows[j][i] -= min_flow; j = i; } max_flow += min_flow; } cout << (max_flow >= sumti ? "Yes" : "No") << endl; } return 0; }
#include<bits/stdc++.h> using namespace std; typedef long long ll; struct edge{ ll to,cap,rev;}; vector<edge> G[110]; void add_edge(ll from,ll to,ll cap){ G[from].push_back( (edge){to,cap, (ll)G[to].size() } ); G[to].push_back( (edge){from,0, (ll)G[from].size()-1} ); } bool visited[110]; ll dfs(ll pos,ll ti,ll f){ if(pos==ti)return f; if(visited[pos])return 0; visited[pos]=true; for(int i=0;i<(int)G[pos].size();i++){ edge &e=G[pos][i]; if(e.cap==0)continue; ll a=dfs(e.to,ti,min(f,e.cap)); if(a==0)continue; e.cap-=a; G[e.to][e.rev].cap+=a; return a; } return 0; } ll max_flow(ll si,ll ti){ ll res=0; while(1){ memset(visited,false,sizeof(visited)); ll f=dfs(si,ti,(1LL<<60)); if(f==0)break; res+=f; } return res; } void init(){ for(int i=0;i<110;i++)G[i].clear(); } map<string,int> mp; ll N,W; int main(){ mp["Sunday"]=0; mp["Monday"]=1; mp["Tuesday"]=2; mp["Wednesday"]=3; mp["Thursday"]=4; mp["Friday"]=5; mp["Saturday"]=6; while(1){ cin>>N>>W; if(N==0&&W==0)break; init(); ll si=7+N,ti=8+N,sum=0; for(int i=0;i<7;i++)add_edge(si,i,W); for(int i=0;i<N;i++){ string str; ll t,c; cin>>t>>c; sum+=t; add_edge(7+i,ti,t); for(int j=0;j<c;j++){ cin>>str; add_edge(mp[str],7+i,W); } } cout<< (max_flow(si,ti)==sum?"Yes":"No") <<endl; } return 0; }
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <memory.h> #include <queue> #include <cstdio> #include <cstdlib> #include <map> #include <cmath> using namespace std; #define rep(i, n) for(int i = 0; i< n; i++) #define rep2(i, m, n) for(int i = m; i < n; i++) typedef long long ll; typedef pair<int, int> P; const ll INF = 1LL << 55; const double EPS = 1e-10; struct edge{ ll to; ll cap; ll rev; edge(){}; edge(ll to, ll cap, ll rev){ this->to = to; this->cap = cap; this->rev = rev; } }; vector<edge> G[400]; ll level[400]; ll iter[400]; void add_edge(ll from, ll to, ll cap){ G[from].push_back(edge(to, cap, G[to].size())); G[to].push_back(edge(from, 0,G[from].size() - 1)); } void bfs(int s){ memset(level, -1, sizeof(level)); level[s] = 0; queue<int> que; que.push(s); while(!que.empty()){ ll v = que.front();que.pop(); rep(i, (int)G[v].size()){ edge &e = G[v][i]; if(e.cap > 0 && level[e.to] < 0) { level[e.to] = level[v] + 1; que.push(e.to); } } } } ll dfs(ll v, ll t, ll f){ if(v == t) return f; for(ll &i = iter[v]; i < (int)G[v].size(); i++){ edge &e = G[v][i]; if(e.cap > 0 && level[e.to] > level[v]){ ll d = dfs(e.to, t, min(f, e.cap)); if(d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } ll max_flow(int s, int t){ ll flow = 0, f; while(true){ bfs(s); if(level[t] < 0) break; memset(iter, 0, sizeof(iter)); while((f = dfs(s, t, INF)) > 0) flow += f; } return flow; } string days[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", }; int main(){ ll N, c; ll W, need; string str; while(cin >> N >> W && (N || W)){ rep(i, 400) G[i].clear(); ll sum = 0; ll s = 7 + N; ll t = s + 1; rep(i, 7) add_edge(s, i, W); rep(i, N){ cin >> need >> c; sum += need; add_edge(7 + i, t, need); rep(j, c){ cin >> str; rep(k, 7) if(days[k] == str) add_edge(k, 7 + i, INF); } } ll num = max_flow(s, t); if(num == sum) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
#include <bits/stdc++.h> using ll = long long; #define int ll #define range(i, a, n) for(int (i) = (a); (i) < (n); (i)++) #define rep(i, n) for(int (i) = 0; (i) < (n); (i)++) using namespace std; using vi = vector<int>; const ll inf = 1L << 50; class dinic{ public : void init(int _n){ n=_n; G.resize(n); iter.resize(n); level.resize(n); } void add_edge(int from,int to ,int cap){ G[from].push_back((edge){to,cap, (int)G[to].size()}); G[to].push_back((edge){from,0, (int)G[from].size()-1}); } void add_edge_both(int from,int to ,int cap){ add_edge(from,to,cap); add_edge(to,from,cap); } int max_flow(int s,int t){ int flow=0; for(;;){ bfs(s); if(level[t]<0) return flow; iter.assign(n,0); int f; while((f=dfs(s,t,DINIC_INF))>0){ flow+=f; } } } private: int n; struct edge{int to,cap,rev;}; static const int DINIC_INF = inf; vector< vector<edge> > G; vi level; vi iter; void bfs(int s){ level.assign(n,-1); queue<int> que; level[s]=0; que.push(s); while(!que.empty()){ int v=que.front();que.pop(); for(int i=0;i< (int)G[v].size(); i++){ edge &e=G[v][i]; if(e.cap>0 && level[e.to] <0){ level[e.to]=level[v]+1; que.push(e.to); } } } } int dfs(int v,int t,int f){ if(v==t) return f; for(int &i=iter[v];i<(int)G[v].size();i++){ edge &e= G[v][i]; if(e.cap>0 && level[v]<level[e.to]){ int d=dfs(e.to,t,min(f,e.cap)); if(d>0){ e.cap -=d; G[e.to][e.rev].cap+=d; return d; } } } return 0; } }; map<string, int> s2i; vector<string> T = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; signed main(void){ rep(i, 7) s2i[T[i]] = i + 1; for(int n, w; cin >> n >> w, n;){ dinic d; d.init(n + 9); range(i, 1, 8){ d.add_edge(0, i, w); } int sum = 0; rep(i, n){ int t, c; cin >> t >> c; sum += t; d.add_edge(9 + i, 8, t); rep(_, c){ string in; cin >> in; int v = s2i[in]; d.add_edge(v, 9 + i, inf); } } if(d.max_flow(0, 8) == sum){ cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <cstring> #include <queue> using namespace std; typedef long long ll; const int MAX_V=1001; const ll INF=1000000000000000LL; class edge{ public: int to,rev; ll cap; edge(int to_,ll cap_,int rev_){ to=to_; cap=cap_; rev=rev_; } }; vector<edge> G[MAX_V]; // s‚©‚ç‚Ì‹——£ int level[MAX_V]; // ‚Ç‚±‚܂Œ²‚׏I‚í‚Á‚½‚© int iter[MAX_V]; void add_edge(int from,int to,ll cap){ G[from].push_back(edge(to,cap,G[to].size())); G[to].push_back(edge(from,0,G[from].size()-1)); } // s‚©‚ç‚̍ŒZ‹——£‚ð‹‚ß‚é void bfs(int s){ memset(level,-1,sizeof(level)); queue<int> que; level[s]=0; que.push(s); while(!que.empty()){ int v=que.front();que.pop(); for(int i=0;i<G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&level[e.to]<0){ level[e.to]=level[v]+1; que.push(e.to); } } } } // ‘‰ÁƒpƒX‚ðdfs‚Å’T‚· ll dfs(int v,int t,ll f){ if(v==t)return f; for(int &i=iter[v];i<G[v].size();i++){ edge &e=G[v][i]; if(e.cap>0&&level[v]<level[e.to]){ ll d=dfs(e.to,t,min(f,e.cap)); if(d>0){ e.cap-=d; G[e.to][e.rev].cap+=d; return d; } } } return 0; } // s‚©‚çt‚ւ̍ő嗬‚ð‹‚ß‚é ll max_flow(int s,int t){ ll flow=0; while(1){ bfs(s); if(level[t]<0)return flow; memset(iter,0,sizeof(iter)); ll f; while((f=dfs(s,t,INF))>0)flow+=f; } } int N; ll W; ll ts[101]; int cs[101]; int main(){ while(cin>>N>>W&&(N|W)){ ll sum=0; for(int i=0;i<MAX_V;i++)G[i].clear(); int sn,gn; for(int i=0;i<N;i++){ cin>>ts[i]>>cs[i]; sum+=ts[i]; // —j“ú‚©‚çl‚Ö for(int j=0;j<cs[i];j++){ string s; cin>>s; int id=0; if(s=="Monday")id=0; else if(s=="Tuesday")id=1; else if(s=="Wednesday")id=2; else if(s=="Thursday")id=3; else if(s=="Friday")id=4; else if(s=="Saturday")id=5; else id=6; add_edge(id,7+i,INF); } } // start‚©‚ç—j“ú‚Ö sn=N+7;gn=sn+1; for(int i=0;i<7;i++)add_edge(sn,i,W); // l‚©‚çgoal‚Ö for(int i=0;i<N;i++)add_edge(7+i,gn,ts[i]); ll res=max_flow(sn,gn); if(res==sum)cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
#include <set> #include <map> #include <iostream> #include <cstdio> #include <algorithm> #include <queue> #define REP(i,n) for(int i=0; i<(int)(n); i++) typedef long long ll; using namespace std; struct Edge{ ll cap; // capacity int to; int rev; // reverse edge id Edge(){} Edge(ll c, int t, int r) : cap(c), to(t), rev(r){} }; template<class E> // Edge type class Graph{ public: typedef std::vector<std::vector<E> > G; private: G g; public: Graph(int n) : g(G(n)) {} void addEdge(int from, int to, ll cap){ g[from].push_back(E(cap, to, g[to].size())); g[to].push_back(E(0, from, g[from].size() - 1)); } G &getRowGraph(){ return g; } }; template<class E> class Dinic{ typedef typename Graph<E>::G G; G &g; std::size_t n; // size of graph std::vector<int> level; std::vector<int> iter; // other utilities // search length of shortest path from s void bfs(int s){ std::queue<int> que; level = std::vector<int>(n, -1); level[s] = 0; que.push(s); while(!que.empty()){ int v = que.front(); que.pop(); for(int i = 0; i < (int)g[v].size(); i++){ E &e = g[v][i]; if(e.cap > 0 && level[e.to] < 0){ level[e.to] = level[v] + 1; que.push(e.to); } } } } // search path ll dfs(int v, int t, ll f){ if(v == t) return f; for(int &i = iter[v]; i < (int)g[v].size(); i++){ E &e = g[v][i]; if(e.cap > 0 && level[v] < level[e.to]){ ll d = dfs(e.to, t, min(f, e.cap)); if(d > 0){ e.cap -= d; g[e.to][e.rev].cap += d; return d; } } } return 0; } public: Dinic(Graph<E> &graph) : g(graph.getRowGraph()){ n = g.size(); } // Max flow of the flow from s to t. ll solve(int s, int t){ ll flow = 0; while(true){ ll f; bfs(s); if(level[t] < 0) return flow; iter = std::vector<int>(n, 0); while((f = dfs(s, t, (1ll << 60))) > 0){ flow += f; } } } }; template<class E> ll dinic(Graph<E> &g, int s, int d){ return Dinic<E>(g).solve(s, d); } template<class T> class IdMaker{ public: std::map<T,int> _m; int getId(const T &v){ if(_m.find(v) == _m.end()){ int next = _m.size(); return _m[v] = next; } return _m[v]; } }; int main(){ while(true){ int n; ll w; ll all = 0; IdMaker<string> idm; cin >> n >> w; if(n + w == 0) break; Graph<Edge> g(n + 7 + 2); const int start = n + 7; const int end = n + 7 + 1; REP(i, 7) g.addEdge(n + i, end, w); REP(i, n){ long long t; int c; cin >> t >> c; all += t; g.addEdge(start, i, t); REP(j, c){ string buff; cin >> buff; int m = idm.getId(buff); g.addEdge(i, n + m, w); } } all -= dinic(g, start, end); puts(all == 0 ? "Yes" : "No"); } return 0; }
#include <cstdio> #include <cstring> #include <vector> #include <string> #include <set> #include <iostream> #include <algorithm> #include <cassert> using namespace std; const int N = 1000 + 10; int n; long long w; int convert(char *x) { if (x[0] == 'S') { if (x[1] == 'u') return 0; return 6; } else if (x[0] == 'T') { if (x[1] == 'u') return 2; return 4; } else if (x[0] == 'M') { return 1; } else if (x[0] == 'W') { return 3; } return 5; assert(0); } void read(long long &x) { char ch; for(ch = getchar(); ch < '0' || ch > '9'; ch = getchar()); for(x = 0; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; } int id[N]; long long a[N]; int s[N]; void solve() { int cnt; char buf[10]; for(int i = 0; i < n; ++ i) { read(a[i]); scanf("%d", &cnt); s[i] = 0; for( ; cnt --; ) { scanf("%s", buf); int x = convert(buf); s[i] |= (1 << x); } } int flag = true; for(int t = 0; t < (1 << 7); ++ t) { long long tmp = 0; for(int i = 0; i < n; ++ i) { if ((s[i] | t) == t) { tmp += a[i]; } } int x = 0; for(int tmp = t; tmp; tmp -= tmp & -tmp) ++ x; if (tmp > x * w) { flag = false; break; } } cout << (flag ? "Yes" : "No") << endl; } int main() { for( ; cin >> n >> w && (n || w); ) { solve(); } return 0; }
#include <bits/stdc++.h> using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) constexpr long long Inf = numeric_limits<long long>::max() / 4; typedef long long ll; namespace flow_algorithm { template<class Flow> struct edge { int to; Flow cap, rev; }; /* template<class Flow> using edges = vector<edge<Flow>>; template<class Flow> using graph = vector<edges<Flow>>; */ typedef vector<edge<ll>> edges; typedef vector<edges> graph; template<class Flow> class ford_fulkerson { private: int V; // graph<Flow> g; graph g; vector<bool> used; // Flow static constexpr Inf = numeric_limits<Flow>::max() / 4; private: Flow dfs(int curr, int tar, Flow flow) { if(curr == tar) { return flow; } used[curr] = true; rep(i, g[curr].size()) { edge<Flow>& e = g[curr][i]; if(!used[e.to] && e.cap > 0) { Flow d = dfs(e.to, tar, min(flow, e.cap)); if(d <= 0) { continue; } e.cap -= d; g[e.to][e.rev].cap += d; return d; } } return 0; } public: ford_fulkerson(int V_) { V = V_; g.resize(V_); used.resize(V_); } void add_edge(int from, int to, Flow cap) { g[from].push_back({to, cap, (Flow)g[to].size()}); g[to].push_back({from, 0, (Flow)g[from].size()-1}); } Flow max_flow(int s, int t) { Flow ret = 0; for(;;) { rep(i, V) used[i] = false; Flow f = dfs(s, t, Inf); if(f == 0) { return ret; } ret += f; } } }; } int const SBASE = 10; int const SRC = 150, SINK = 151; int main() { map<string, int> mp = { {"Monday",0}, {"Tuesday", 1}, {"Wednesday", 2}, {"Thursday", 3}, {"Friday", 4}, {"Saturday", 5}, {"Sunday", 6} }; int N; ll W; while(cin >> N >> W && (N|W)) { flow_algorithm::ford_fulkerson<ll> ff(200); rep(i, 7) ff.add_edge(SRC, i, W); ll need = 0; rep(i, N) { ll t; int c; cin >> t >> c; need += t; rep(j, c) { string s; cin >> s; // dn.add_edge(mp[s], SBASE+i, flow_algorithm::dinic<ll>::Inf); ff.add_edge(mp[s], SBASE+i, Inf); } ff.add_edge(SBASE+i, SINK, t); } cout << ( ff.max_flow(SRC, SINK) == need ? "Yes" : "No" ) << endl; } return 0; }
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; typedef ll Weight; struct Edge { int src, dst; Weight weight; Edge(int src, int dst, Weight weight) : src(src), dst(dst), weight(weight) { } }; typedef vector<Edge> Edges; typedef vector<Edges> Graph; typedef vector<Weight> Array; typedef vector<Array> Matrix; void add_edge2(Graph &g, int s, int d, Weight w){ g[s].push_back(Edge(s,d,w)); g[d].push_back(Edge(d,s,0)); } #define RESIDUE(s,t) (capacity[s][t]-flow[s][t]) Weight augment(const Graph &g, const Matrix &capacity, Matrix &flow, const vector<int> &level, vector<bool> &finished, int u, int t, Weight cur) { if (u == t || cur == 0) return cur; if (finished[u]) return 0; finished[u] = true; FOR(e, g[u]) if (level[e->dst] > level[u]) { Weight f = augment(g, capacity, flow, level, finished, e->dst, t, min(cur, RESIDUE(u, e->dst))); if (f > 0) { flow[u][e->dst] += f; flow[e->dst][u] -= f; finished[u] = false; return f; } } return 0; } Weight maximumFlow(const Graph &g, int s, int t) { int n = g.size(); Matrix flow(n, Array(n)), capacity(n, Array(n)); // adj. matrix REP(u,n) FOR(e,g[u]) capacity[e->src][e->dst] += e->weight; Weight total = 0; for (bool cont = true; cont; ) { cont = false; vector<int> level(n, -1); level[s] = 0; // make layered network queue<int> Q; Q.push(s); for (int d = n; !Q.empty() && level[Q.front()] < d; ) { int u = Q.front(); Q.pop(); if (u == t) d = level[u]; FOR(e, g[u]) if (RESIDUE(u,e->dst) > 0 && level[e->dst] == -1) Q.push(e->dst), level[e->dst] = level[u] + 1; } vector<bool> finished(n); // make blocking flows for (Weight f = 1; f > 0; ) { f = augment(g, capacity, flow, level, finished, s, t, INF); if (f == 0) break; total += f; cont = true; } } return total; } ll n,w; int NODE(int i) { return i; } int SRC() { return n+7; } int SINK() { return n+8; } int DAY(int i) { return n+i; } int main() { string hoge[] = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"}; map<string, int> mp; REP(i,7) mp[hoge[i]] = i; while(cin >> n >> w, n||w) { Graph g(n+7+2); ll sum = 0; REP(i, n) { ll t, c; cin >> t >> c; add_edge2(g, SRC(), NODE(i), t); sum += t; REP(j, c) { string s; cin >> s; add_edge2(g, NODE(i), DAY(mp[s.substr(0,3)]), 1LL<<60); } } REP(i, 7) { add_edge2(g, DAY(i), SINK(), w); } // FOR(it, g) { // FOR(jt, *it) printf("(%d->%d)%lld ", jt->src, jt->dst, jt->weight); // cout << endl; // } if (maximumFlow(g, SRC(), SINK()) == sum) { cout << "Yes" << endl; } else { cout << "No" << endl; } } }
#include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; using ll = long long; struct Data { ll h, a, d, s; Data() {} Data(ll h, ll a, ll d, ll s) : h{h}, a{a}, d{d}, s{s} {} bool operator < (const Data& d) const { return s < d.s; } }; istream& operator >> (istream& is, Data& d) { return is >> d.h >> d.a >> d.d >> d.s; } ll solve(Data& M, vector<Data>& ene) { vector<pair<double, Data>> v; for (const Data& e : ene) { if (M.a <= e.d && M.d < e.a) return -1; ll turn = ceil((double)e.h / (M.a - e.d)); if (e.a - M.d <= 0) continue; v.emplace_back((double)turn / (e.a - M.d), e); } sort(v.begin(), v.end()); ll res = 0, total_turn = 0; for (const auto& d : v) { Data e = d.second; ll turn = ceil((double)e.h / (M.a - e.d)); total_turn += turn; ll damage = (total_turn - (M.s > e.s)) * max(0LL, e.a - M.d); M.h -= damage; if (M.h <= 0) return -1; res += damage; } return res; } int main() { int N; cin >> N; Data M; cin >> M; vector<Data> ene(N); for (int i = 0; i < N; i++) { cin >> ene[i]; } cout << solve(M, ene) << endl; return 0; }
//////////////////////////////////////// /// tu3 pro-con template /// //////////////////////////////////////// #include <cassert> #include <cstdio> #include <cstring> #include <cmath> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <vector> #include <queue> #include <string> #include <complex> #include <stack> #include <set> #include <map> #include <list> #include <unordered_map> #include <unordered_set> #include <bitset> #include <regex> using namespace std; //// MACRO //// #define countof(a) (sizeof(a)/sizeof(a[0])) #define REP(i,n) for (int i = 0; i < (n); i++) #define RREP(i,n) for (int i = (n)-1; i >= 0; i--) #define FOR(i,s,n) for (int i = (s); i < (n); i++) #define RFOR(i,s,n) for (int i = (n)-1; i >= (s); i--) #define pos(c,i) c.being() + (i) #define allof(c) c.begin(), c.end() #define aallof(a) a, countof(a) #define partof(c,i,n) c.begin() + (i), c.begin() + (i) + (n) #define apartof(a,i,n) a + (i), a + (i) + (n) #define long long long #define EPS 1e-9 #define INF (1L << 30) #define LINF (1LL << 60) #define PREDICATE(t,a,exp) [&](const t & a) -> bool { return exp; } #define COMPARISON_T(t) bool(*)(const t &, const t &) #define COMPARISON(t,a,b,exp) [&](const t & a, const t & b) -> bool { return exp; } #define CONVERTER(TSrc,t,TDest,exp) [&](const TSrc &t)->TDest { return exp; } inline int sign(double x) { return (abs(x) < EPS ? 0 : x > 0 ? 1 : -1); } inline bool inRange(int val, int min, int max) { return val >= min && val < max; } inline bool inRange(double val, double min, double max) { return val - min > -EPS && val - max < EPS; } template <class T> struct vevector : public vector<vector<T>> { vevector(int n = 0, int m = 0, const T &initial = T()) : vector<vector<T>>(n, vector<T>(m, initial)) { } }; template <class T> struct vevevector : public vector<vevector<T>> { vevevector(int n = 0, int m = 0, int l = 0, const T &initial = T()) : vector<vevector<T>>(n, vevector<T>(m, l, initial)) { } }; template <class T> struct vevevevector : public vector<vevevector<T>> { vevevevector(int n = 0, int m = 0, int l = 0, int k = 0, const T &initial = T()) : vector<vevevector<T>>(n, vevevector<T>(m, l, k, initial)) { } }; //// i/o helper //// #ifdef _DEBUG #define DEBUG WRITE inline void readfrom(string filename) { freopen(filename.c_str(), "r", stdin); } inline void writeto(string filename) { freopen(filename.c_str(), "w", stdout); } #else #define DEBUG(...) inline void readfrom(...) { } inline void writeto(...) { } #endif #ifdef ccout # define cout ccout # define endl cendl #endif struct _Reader { template <class T> _Reader operator ,(T &rhs) { cin >> rhs; return *this; } }; struct _Writer { bool f; _Writer() : f(false) { } template <class T> _Writer operator ,(const T &rhs) { cout << (f ? " " : "") << rhs; f = true; return *this; } }; #define READ(t,...) t __VA_ARGS__; _Reader(), __VA_ARGS__ #define WRITE(...) _Writer(), __VA_ARGS__; cout << endl template <class T> T read() { T t; cin >> t; return t; } template <class T> vector<T> read(int n) { vector<T> v; REP(i, n) { v.push_back(read<T>()); } return v; } template <class T> vevector<T> read(int n, int m) { vevector<T> v; REP(i, n) v.push_back(read<T>(m)); return v; } template <class T> vevector<T> readjag() { return read<T>(read<int>()); } template <class T> vevector<T> readjag(int n) { vevector<T> v; REP(i, n) v.push_back(readjag<T>()); return v; } template <class T1, class T2> inline istream & operator >> (istream & in, pair<T1, T2> &p) { in >> p.first >> p.second; return in; } template <class T1, class T2> inline ostream & operator << (ostream &out, pair<T1, T2> &p) { out << p.first << p.second; return out; } template <class T> inline ostream & operator << (ostream &out, const vector<T> &v) { ostringstream ss; for (auto x : v) ss << x << ' '; auto s = ss.str(); out << s.substr(0, s.length() - 1) << endl; return out; } //// start up //// void solve(); int main() { solve(); return 0; } //////////////////// /// template end /// //////////////////// void solve() { int testcases = 1; REP(testcase, testcases) { READ(int, n); READ(long, hp, pa, pd, ps); struct E { long h, a, d, s; }; vector<E> op; REP(i, n) { READ(int, h, a, d, s); op.push_back({ h, a, d, s }); } struct C { long a, d, t; double priority; }; vector<C> enemies; bool muri = false; long dmgPerTurn = 0; long dmg = 0; REP(i, n) { E e = op[i]; int aa = max(e.a - pd, 0ll); int dd = max(pa - e.d, 0ll); if (dd == 0 && aa != 0) { muri = true; break; } if (dd == 0) { continue; } int tt = (e.h + dd - 1) / dd; // 倒すのに掛かるターン数 double priority = (double)tt / aa; enemies.push_back({ aa, dd, tt, priority }); if (e.s > ps) { dmg += aa; } // 相手の先制 dmgPerTurn += aa; } if (muri) { WRITE(-1); continue; } // 倒す順番 sort(allof(enemies), COMPARISON(C, a, b, a.priority < b.priority)); for (auto e : enemies) { long t = e.t; dmg += t * dmgPerTurn - e.a; if (dmg >= hp) { break; } dmgPerTurn -= e.a; } WRITE(dmg < hp ? dmg : -1); } }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> P; typedef pair<int,P> P1; typedef pair<P,P> P2; #define pu push #define pb push_back #define mp make_pair #define eps 1e-7 #define INF 1000000000 #define fi first #define sc second #define rep(i,x) for(int i=0;i<x;i++) #define SORT(x) sort(x.begin(),x.end()) #define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end()) #define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin()) #define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin()) ll n,h[40005],a[40005],d[40005],s[40005]; vector<pair<pair<ll,ll>,int> >M; bool cmp(const pair<pair<ll,ll>,int> &a,const pair<pair<ll,ll>,int> &b){ return 1LL*a.fi.fi*b.fi.sc < 1LL*b.fi.fi*a.fi.sc; } int main(){ cin >> n; for(int i=0;i<=n;i++) cin >> h[i] >> a[i] >> d[i] >> s[i]; ll C = 0; for(int i=1;i<=n;i++){ if(a[i] <= d[0]){ continue; } if(a[0] <= d[i]){ puts("-1"); return 0; } C += (a[i]-d[0]); M.pb(mp( mp( (h[i]+a[0]-d[i]-1)/(a[0]-d[i]),a[i]-d[0]) , i )); } sort(M.begin(),M.end(),cmp); ll cur = 0; for(int i=0;i<M.size();i++){ int m = M[i].sc; ll T = (h[m]+a[0]-d[m]-1)/(a[0]-d[m]); cur += 1LL * T * C; if(s[m] < s[0]) cur -= (a[m]-d[0]); if(cur >= h[0]){ puts("-1"); return 0; } C -= (a[m]-d[0]); } printf("%lld\n",cur); }
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for (int i=0; i<(n); ++i) #define RREP(i, n) for (int i=(int)(n)-1; i>=0; --i) #define FOR(i, a, n) for (int i=(a); i<(n); ++i) #define RFOR(i, a, n) for (int i=(int)(n)-1; i>=(a); --i) #define SZ(x) ((int)(x).size()) #define all(x) begin(x),end(x) #define dump(x) cerr<<#x<<" = "<<(x)<<endl #define debug(x) cerr<<#x<<" = "<<(x)<<" (L"<<__LINE__<<")"<<endl; template<class T> ostream &operator<<(ostream &os, const vector <T> &v) { os << "["; REP(i, SZ(v)) { if (i) os << ", "; os << v[i]; } return os << "]"; } template<class T, class U> ostream &operator<<(ostream &os, const pair <T, U> &p) { return os << "(" << p.first << " " << p.second << ")"; } template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template<class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } using ll = long long; using ull = unsigned long long; using ld = long double; using P = pair<int, int>; using vi = vector<int>; using vll = vector<ll>; using vvi = vector<vi>; using vvll = vector<vll>; const ll MOD = 1e9 + 7; const int INF = INT_MAX / 2; const ll LINF = LLONG_MAX / 2; const ld eps = 1e-9; int main() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(10); ll ans = 0; int n; cin >> n; ll H, A, D, S; cin >> H >> A >> D >> S; vll t, b, u; REP(i, n) { int h, a, d, s; cin >> h >> a >> d >> s; int dam2p = max(a - D, 0LL); if (dam2p == 0) continue; int dam2this = max(A - d, 0LL); if (dam2this == 0) { ans = -1; continue; } t.push_back((h-1) / dam2this + 1); b.push_back(dam2p); u.push_back(S > s); } if (ans == -1) { cout << -1 << endl; return 0; } n = t.size(); vi ord(n); iota(all(ord), 0); sort(all(ord), [&](int i,int j){ return (double)t[i] / b[i] < (double)t[j] / b[j]; }); ll tsum = 0; for (int i : ord) { tsum += t[i]; ans += (tsum - u[i]) * b[i]; if (ans >= H) { ans = -1; break; } } cout << ans << endl; return 0; }
#include <bits/stdc++.h> #define rep(i,n) for(int i=0; i<(int)(n); ++i) using namespace std; typedef long long ll; struct chara{ ll h, a, d, s, t; bool operator < (const chara& c) const { return t * c.a < c.t * a; } }; ll solve(int n){ chara me; cin >> me.h >> me.a >> me.d >> me.s; vector<chara> rival(n); for(chara& c : rival){ cin >> c.h >> c.a >> c.d >> c.s; c.a = max(0ll, c.a - me.d); } for(chara& c : rival){ if(me.a <= c.d){ if(c.a > 0){ return -1; }else{ c.d = 0; } } } for(chara& c : rival){ c.t = (c.h + me.a - c.d - 1) / (me.a - c.d); } ll sum = 0; for(const chara& c : rival){ if(c.s < me.s){ sum -= c.a; } } sort(rival.begin(), rival.end()); ll time = 0; for(const chara& c : rival){ time += c.t; sum += c.a * time; if(sum >= me.h) { return -1; } } return sum; } int main(){ int n; while(cin >> n){ cout << solve(n) << endl; } return 0; }
//AOJ 2236 #include<iostream> #include<vector> #include<string> #include<algorithm> #include<map> #include<set> #include<utility> #include<cmath> #include<cstring> #include<queue> #include<stack> #include<cstdio> #include<sstream> #include<iomanip> #include<assert.h> #define loop(i,a,b) for(int i=a;i<b;i++) #define rep(i,a) loop(i,0,a) #define pb push_back #define all(in) in.begin(),in.end() #define shosu(x) fixed<<setprecision(x) using namespace std; //kaewasuretyuui typedef long long ll; typedef ll Def; typedef pair<Def,Def> pii; typedef vector<Def> vi; typedef vector<vi> vvi; typedef vector<pii> vp; typedef vector<vp> vvp; typedef vector<string> vs; typedef vector<double> vd; typedef vector<vd> vvd; typedef pair<Def,pii> pip; typedef vector<pip>vip; //#define mt make_tuple //typedef tuple<double,int,double> tp; //typedef vector<tp> vt; template<typename A,typename B>bool cmin(A &a,const B &b){return a>b?(a=b,true):false;} template<typename A,typename B>bool cmax(A &a,const B &b){return a<b?(a=b,true):false;} const double PI=acos(-1); const double EPS=1e-7; Def inf = sizeof(Def) == sizeof(long long) ? 2e18 : 1e9; int dx[]={0,1,0,-1}; int dy[]={1,0,-1,0}; int main(){ int n; cin>>n; vp in; int a1,b1,c1,d1; cin>>a1>>b1>>c1>>d1; bool h=false; ll out=0; rep(i,n){ int a,b,c,d; cin>>a>>b>>c>>d; if(d1>d)out-=max(0,b-c1); if(b1-c>0)in.pb(pii(max(0,b-c1),(a+b1-c-1)/(b1-c))); else if(b-c1<=0); else h=true; } if(h){ cout<<-1<<endl; return 0; } sort(all(in),[](pii a,pii b){ return a.second*b.first<a.first*b.second; }); ll co=0; // rep(i,in.size())cout<<in[i].first<<" "<<in[i].second<<endl; rep(i,in.size()){ co+=in[i].second; if(out!=-inf)out+=co*in[i].first; // cout<<out<<endl; if(out>=a1)out=-inf; if(out==-inf)break; } if(out==-inf)cout<<-1<<endl; else cout<<out<<endl; }
#include <bits/stdc++.h> using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int, int> PII; typedef long long LL; typedef pair<LL, LL> PLL; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(), (a).rend() #define PB push_back #define EB emplace_back #define MP make_pair #define SZ(a) int((a).size()) #define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i) #define EXIST(s,e) ((s).find(e)!=(s).end()) #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define FF first #define SS second template<class S, class T> istream& operator>>(istream& is, pair<S,T>& p){ return is >> p.FF >> p.SS; } const double EPS = 1e-10; const double PI = acos(-1.0); const LL MOD = 1e9+7; int main(){ cin.tie(0); ios_base::sync_with_stdio(false); int N; cin >> N; LL mh, ma, md, ms; cin >> mh >> ma >> md >> ms; vector<PLL> en; LL dsum = 0; REP(i,N){ LL h, a, d, s; cin >> h >> a >> d >> s; if(ma <= d){ if(a-md > 0){ cout << -1 << endl; return 0; } continue; } en.EB((h - 1) / (ma - d) + 1, max(0LL,a-md)); if(s < ms) dsum -= en.back().SS; } N = SZ(en); sort(ALL(en), [](PLL& p1, PLL& p2){ return p1.FF*p2.SS < p1.SS*p2.FF; }); LL tsum = 0; for(int i=0;i<N;++i){ tsum += en[i].FF; dsum += tsum * en[i].SS; if(dsum >= mh) break; } cout << (dsum >= mh? -1: dsum) << endl; return 0; }
#include <cstdio> #include <iostream> #include <algorithm> #include <map> #define F first #define S second using namespace std; int n; //long long int ph,pa,pd,ps; long long int h[44444]; long long int a[44444]; long long int b[44444]; long long int s[44444]; pair<long double,int> p[44444]; long long int ad; int main(void){ cin >> n /*>> ph >> pa >> pd >> ps*/; for(int i = 0; i <= n; i++){ cin >> h[i] >> a[i] >> b[i] >> s[i]; } for(int i = 1; i <= n; i++){ ad += max(a[i] - b[0],0LL); if(a[0] - b[i] <= 0){ p[i-1].F = -1; }else{ p[i-1].F = (long double)max(a[i] - b[0],0LL) / (long long int)((h[i]+a[0]-b[i]-1)/(a[0]-b[i])); } p[i-1].S = i; } sort(p,p+n,greater< pair<long double,int> >()); long long int d = 0; for(int i = 0; i < n; i++){ int pp = p[i].S; if(p[i].F >= 0){ d += ad * ((h[pp]+a[0]-b[pp]-1)/(a[0]-b[pp])); if(s[0] > s[pp]) d -= max(a[pp] - b[0],0LL); }else if(max(a[pp]-b[0],0LL)){ d += h[0]; } if(h[0] <= d){ cout << -1 << endl; return 0; } //cout << pp << endl; ad -= max(a[pp] - b[0],0LL); } cout << d << endl; }
#include "bits/stdc++.h" using namespace std; using ll = long long; using ld = long double; using P = pair<int, int>; constexpr ld EPS = 1e-12; constexpr int INF = numeric_limits<int>::max() / 2; constexpr int MOD = 1e9 + 7; template <typename T> void printv(const vector<T> &v) { int sz = v.size(); for (int i = 0; i < sz; i++) { cout << v[i] << " \n"[i == sz - 1]; } } int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; ll hp, atk, def, spd; cin >> hp >> atk >> def >> spd; vector<ll> h, a, d, s; for (int i = 0; i < n; i++) { ll htmp, atmp, dtmp, stmp; cin >> htmp >> atmp >> dtmp >> stmp; if (dtmp >= atk && atmp > def) { cout << -1 << endl; return 0; } if (atmp <= def) continue; atmp -= def; h.push_back(htmp); a.push_back(atmp); d.push_back(dtmp); s.push_back(stmp); } n = h.size(); vector<ll> turn(n), dmg(n); for (int i = 0; i < n; i++) { dmg[i] = a[i]; ll tmp = atk - d[i]; turn[i] = (h[i] - 1) / tmp + 1; } vector<int> idx(n); for (int i = 0; i < n; i++) idx[i] = i; sort(idx.begin(), idx.end(), [&](int i, int j) { return turn[i] * dmg[j] < turn[j] * dmg[i]; }); ll ret = 0, cnt = 0; for (auto i : idx) { hp -= cnt * a[i]; ret += cnt * a[i]; if (hp <= 0) { cout << -1 << endl; return 0; } cnt += turn[i]; if (s[i] > spd) { hp -= turn[i] * a[i]; ret += turn[i] * a[i]; } else { turn[i]--; hp -= turn[i] * a[i]; ret += turn[i] * a[i]; } if (hp <= 0) { cout << -1 << endl; return 0; } } cout << ret << endl; }
#include <bits/stdc++.h> using namespace std; typedef long long int64; int main() { int64 N, H[40001], A[40001], D[40001], S[40001]; scanf("%lld", &N); for(int i = 0; i < N + 1; i++) { scanf("%lld %lld %lld %lld", H + i, A + i, D + i, S + i); } int64 ret = 0; int64 turn = 0; vector< pair< int64, int64 > > xs; for(int i = 1; i <= N; i++) { int64 GetDamage = A[i] - D[0]; int64 AddDamage = A[0] - D[i]; if(GetDamage <= 0) continue; if(S[i] > S[0]) ret += GetDamage; if(AddDamage <= 0) { puts("-1"); return (0); } xs.emplace_back((H[i] + AddDamage - 1) / AddDamage, GetDamage); turn += GetDamage; } sort(begin(xs), end(xs), [](const pair< int64, int64 > &a, const pair< int64, int64 > &b) { return (a.first * b.second < b.first * a.second); }); for(auto &p : xs) { ret += turn * p.first - p.second; if(ret >= H[0]) { puts("-1"); return (0); } turn -= p.second; } printf("%lld\n", max(-1LL, ret)); }
#include<bits/stdc++.h> using namespace std; typedef long long ll; int N,H,A,D,S; int h,a,d,s; vector<ll> x,y; int t[40000]; ll sum,cnt; bool f(const int &a,const int &b){ ll A=x[a]*(y[a]-1)+x[b]*(y[a]+y[b]-1); ll B=x[b]*(y[b]-1)+x[a]*(y[a]+y[b]-1); return (A<B); } int solve(){ N=x.size(); for(int i=0;i<N;i++){ t[i]=i; cnt+=x[i]; } if(H<=sum)return -1; sort(t,t+N,f); for(int i=0;i<N;i++){ int id=t[i]; sum+=x[id]*(y[id]-1); cnt-=x[id]; sum+=cnt*y[id]; if(H<=sum)return -1; } return sum; } int main(){ scanf("%d %d %d %d %d",&N,&H,&A,&D,&S); for(int i=0;i<N;i++){ scanf("%d %d %d %d",&h,&a,&d,&s); if(s>S)sum+=(max(a-D,0)); if( a-D <= 0 )continue; if( A-d <= 0 ){ cout<<-1<<endl; return 0; } x.push_back( a-D ); y.push_back( (h+A-d-1)/(A-d) ); } cout<<solve()<<endl; return 0; }
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <queue> #include <set> #include <map> #include <cmath> using namespace std; typedef long long i64; typedef long double ld; #define rep(i,s,e) for(int i = (s);i <= (e);i++) int n; i64 h[40404]; i64 a[40404]; i64 d[40404]; i64 s[40404]; i64 A[40404]; i64 B[40404]; i64 ceil(i64 A,i64 B){ return A / B + min(1LL,A % B); } int main(){ cin >> n; vector<int> vec; rep(i,0,n){ cin >> h[i] >> a[i] >> d[i] >> s[i]; if(i == 0) continue; //cant if(a[0] <= d[i] && a[i] > d[0]){ cout << -1 << endl; return 0; } if(a[0] > d[i]){ vec.push_back(i); A[i] = (ceil(h[i],a[0] - d[i])); B[i] = (max(0LL,a[i] - d[0])); } } auto ope = [&](int i,int j){ return A[i] * B[j] < A[j] * B[i]; }; sort(vec.begin(),vec.end(),ope); i64 HP = 0; i64 cou = 0; rep(i,0,(int)vec.size() - 1){ int index = vec[i]; cou += A[index]; HP += cou * B[index]; if(s[index] < s[0]) HP -= B[index]; if(h[0] <= HP){ cout << -1 << endl; return 0; } } cout << HP << endl; return 0; }
#include <iostream> #include <vector> #include <algorithm> #include <cstdio> #include <numeric> #define REP(i,n) for(int i=0; i<(int)(n); i++) using namespace std; typedef long long ll; inline int getInt(){ int s; scanf("%d", &s); return s; } int main(){ int n = getInt(); vector<int> h(n); vector<int> a(n); vector<int> d(n); vector<int> s(n); vector<int> memo(n); vector<pair<double, int> > c(n); int hh = getInt(); int aa = getInt(); int dd = getInt(); int ss = getInt(); ll ans = 0; ll tm = 0; REP(i,n){ h[i] = getInt(); a[i] = getInt(); d[i] = getInt(); s[i] = getInt(); ll dam = aa - d[i]; if(dam <= 0){ if(a[i] - dd <= 0){ i--; n--; continue; }else{ goto bad; } } memo[i] = (h[i] + dam - 1) / dam; if(s[i] > ss) c[i].first = (double)max(0, a[i] - dd) / (memo[i]); else c[i].first = (double)max(0, a[i] - dd) / (memo[i]); c[i].second = i; } c.resize(n); sort(c.rbegin(), c.rend()); REP(i,n){ int ii = c[i].second; int tt = memo[ii] - 1; if(s[ii] > ss) tt++; ans += (tm + tt) * max(0, a[ii] - dd); if(ans >= hh) goto bad; tm += memo[ii]; } printf("%d\n", (int)ans); return 0; bad: puts("-1"); return 0; }
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #include<utility> #include<complex> #include<functional> using namespace std; /* constant */ const int MAX_N = 40000; const long long INF = 1LL << 60; /* typedef */ typedef long long ll; /* global variables */ int n, m; ll h0, a0, d0, s0; ll hs[MAX_N], as[MAX_N], ds[MAX_N], ss[MAX_N]; ll tns[MAX_N], dms[MAX_N]; int ids[MAX_N]; /* subroutines */ bool idcmp(const int& a, const int& b) { return tns[a] * dms[b] < tns[b] * dms[a]; } /* main */ int main() { cin >> n; cin >> h0 >> a0 >> d0 >> s0; m = 0; for (int i = 0; i < n; i++) { cin >> hs[i] >> as[i] >> ds[i] >> ss[i]; int ai = a0 - ds[i], di = as[i] - d0; tns[i] = (ai > 0) ? (hs[i] + ai - 1) / ai : INF; dms[i] = (di > 0) ? di : 0; if (ai <= 0 && di > 0) { cout << -1 << endl; return 0; } if (di > 0) ids[m++] = i; } sort(ids, ids + m, idcmp); ll dsum = 0, tnsum = 0; for (int i = 0; i < m; i++) { int id = ids[i]; //printf("id=%d, tns[id]=%lld, dms[id]=%lld\n", id, tns[id], dms[id]); tnsum += tns[id]; dsum += (s0 > ss[id] ? tnsum - 1 : tnsum) * dms[id]; if (dsum >= h0) { dsum = -1; break; } } cout << dsum << endl; return 0; }
#include<iostream> #include<sstream> #include<algorithm> #include<set> #include<map> #include<queue> #include<complex> #include<cstdio> #include<cstdlib> #include<cstring> #include<cassert> #define rep(i,n) for(int i=0;i<(int)n;i++) #define all(c) (c).begin(),(c).end() #define mp make_pair #define pb push_back #define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++) #define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; const int inf = (int)1e9; const double INF = 1e12, EPS = 1e-9; ll n, h, a, d, s; struct E{ ll h, a, d, s, t; }; bool cmp(const E &a, const E &b){ ll da = a.a - d, db = b.a - d; return a.t * db < b.t * da; } int main(){ cin >> n >> h >> a >> d >> s; vector<E> es; rep(i, n){ E e; cin >> e.h >> e.a >> e.d >> e.s; ll k = a - e.d; if(e.a <= d) continue; if(k <= 0){ cout << -1 << endl; return 0; } else{ e.t = (e.h + k - 1) / k; es.pb(e); } } sort(all(es), cmp); ll ans = 0, turn = 0; rep(i, es.size()){ turn += es[i].t; ans += (es[i].a - d) * (turn - (s > es[i].s)); if(ans >= h){ cout << -1 << endl; return 0; } } cout << ans << endl; return 0; }
#include <cstdio> #include <cstring> #include <vector> #include <queue> #include <string> #include <algorithm> #include <iostream> #include <string> #include <map> #include <set> #include <functional> #include <iostream> #define MOD 1000000007LL using namespace std; typedef long long ll; typedef pair<int,int> P; int n; ll ma,md,ms,mh; struct data{ ll h,a,d,s; data(){} data(ll hh,ll aa,ll dd,ll ss){ h=hh; a=aa; d=dd; s=ss; } bool operator <(const data& da)const{ ll turn=(h+(ma-d-1LL))/(ma-d); ll dturn=(da.h+(ma-da.d-1LL))/(ma-da.d); ll sum=turn*max(0LL,a-md)+(turn+dturn)*max(0LL,da.a-md); ll dsum=(turn+dturn)*max(0LL,a-md)+dturn*max(0LL,da.a-md); return sum<dsum; } }; vector<data> vec; int main(void){ scanf("%d",&n); ll sum=0; scanf("%lld%lld%lld%lld",&mh,&ma,&md,&ms); for(int i=0;i<n;i++){ ll h,a,d,s; scanf("%lld%lld%lld%lld",&h,&a,&d,&s); if(ma-d<=0LL){ if(a-md>0){ printf("-1\n"); return 0; } }else{ sum+=max(0LL,a-md); vec.push_back(data(h,a,d,s)); } } sort(vec.begin(),vec.end()); ll res=0; for(int i=0;i<vec.size();i++){ ll turn=(vec[i].h+(ma-vec[i].d-1LL))/(ma-vec[i].d); res+=turn*sum; if(vec[i].s<ms)res-=max(0LL,vec[i].a-md); if(res>=mh){ printf("-1\n"); return 0; } sum-=max(0LL,vec[i].a-md); } printf("%lld\n",res); return 0; }
#include<bits/stdc++.h> using namespace std; struct info{ long long i, a, m; double key; info(long long i, long long a, long long m, double key):i(i),a(a),m(m),key(key){} info(){} bool operator<(const info& aa) const{ return key < aa.key; } bool operator>(const info& aa) const{ return key > aa.key; } }; int main(){ int n; cin >> n; long long rh, ra, rd, rs; cin >> rh >> ra >> rd >> rs; long long H = rh; vector<info> array(n); long long sum_a = 0LL; for(int i = 0; i < n; i++){ long long h, a, d, s; cin >> h >> a >> d >> s; if(s > rs) rh -= max(0LL, a - rd); //cout << ra - d << endl; if(ra - d <= 0 && a - rd > 0){ for(int j = i + 1; j < n; j++) cin >> h >> a >> d >> s; //cout << "hoge" << endl; cout << -1 << endl; return 0; } if(ra - d > 0) array[i] = info(i, max(0LL, a - rd), (h + (ra - d) - 1) / (ra - d), 1); else array[i] = info(i, 0, 0, 0); sum_a += array[i].a; } for(int i = 0; i < n; i++){ if(array[i].key == 0) continue; array[i].key = (double)array[i].a / array[i].m; } sort(array.begin(), array.end()); reverse(array.begin(), array.end()); for(int i = 0; i < n; i++){ //cout << "i= " << i << "rh= " << rh << " array[i].a = " << array[i].a << " array[i].m = " << array[i].m << " array[i].key = " << array[i].key << endl; rh -= (array[i].m - 1) * sum_a; if(rh < 0){ //cout << "huhuhuhga" << endl; cout << -1 << endl; return 0; } sum_a -= array[i].a; rh -= sum_a; } //cout << rh << endl; if(rh <= 0){ //cout << "piyo" << endl; cout << -1 << endl; return 0; }else{ cout << H - rh << endl; } return 0; }
#include <algorithm> #include <cmath> #include <cstdlib> #include <iostream> #include <vector> using namespace std; #define dump(a) (cerr << #a << " = " << (a) << endl) struct data { int turn, damage, idx; data(int t, int d, int i):turn(t), damage(d), idx(i){} bool operator<(const data& d) const { return (double)damage / turn < (double)d.damage / d.turn; } }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> h(n + 1), a(n + 1), d(n + 1), s(n + 1); for(int i = 0; i < n + 1; ++i) cin >> h[i] >> a[i] >> d[i] >> s[i]; vector<data> dat; dat.reserve(n); for(int i = 1; i < n + 1; ++i) { const int attack = max(0, a[0] - d[i]); const int damage = max(0, a[i] - d[0]); if(attack == 0) { if(damage == 0) continue; cout << -1 << endl; return EXIT_SUCCESS; } const int turn = ceil((double)h[i] / attack); dat.push_back(data(turn, damage, i)); } sort(dat.rbegin(), dat.rend()); long long turn = 0, hp = h[0]; for(int i = 0; i < n; ++i) { turn += dat[i].turn; hp -= dat[i].damage * (turn - (s[0] > s[dat[i].idx] ? 1 : 0)); if(hp <= 0) { cout << -1 << endl; return EXIT_SUCCESS; } } cout << h[0] - hp << endl; return EXIT_SUCCESS; }
#include <iostream> #include <cstdio> #include <vector> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <cstring> #include <functional> #include <cmath> #include <complex> using namespace std; #define rep(i,n) for(int i=0;i<(n);++i) #define rep1(i,n) for(int i=1;i<=(n);++i) #define all(c) (c).begin(),(c).end() #define fs first #define sc second #define pb push_back #define show(x) cout << #x << " " << x << endl typedef long long ll; typedef pair<ll,ll> P; typedef pair<int,P> PP; ll dam[40000],t[40000],inf=1e9; vector<PP> ord; bool comp(const PP& x,const PP& y){ return x.sc.fs*y.sc.sc>x.sc.sc*y.sc.fs; } vector<int> uses; int main(){ int N; ll H,A,D,S,turn=0,sum=0; cin>>N; cin>>H>>A>>D>>S; rep(i,N){ ll h,a,d,s; cin>>h>>a>>d>>s; dam[i]=max((ll)0,a-D); if(A-d>0){ t[i]=(h-1)/(A-d)+1; turn+=t[i]; } else t[i]=-1; if(S<s) sum+=dam[i]; } rep(i,N){ if(!dam[i]) continue; if(t[i]<0){ puts("-1"); return 0; } uses.pb(i); } for(int i:uses) ord.pb(PP(i,P(dam[i],t[i]))); sort(all(ord),comp); rep(i,ord.size()) dam[i]=ord[i].sc.fs,t[i]=ord[i].sc.sc; ll tmp=-1; rep(i,ord.size()){ // show(t[i]); // show(dam[i]); tmp+=t[i]; sum+=dam[i]*tmp; if(H-sum<=0){ puts("-1"); return 0; } } cout<<sum<<endl; }
#include <bits/stdc++.h> using namespace std; #define dump(n) cout<<"# "<<#n<<'='<<(n)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp make_pair #define mt make_tuple typedef unsigned int uint; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<string> vs; const int INF=1e9; const int MOD=1e9+7; const double EPS=1e-9; template<typename T1,typename T2> ostream& operator<<(ostream& os,const pair<T1,T2>& p){ return os<<'('<<p.first<<','<<p.second<<')'; } template<typename T> ostream& operator<<(ostream& os,const vector<T>& a){ os<<'['; rep(i,a.size()) os<<(i?" ":"")<<a[i]; return os<<']'; } void permute(vi& a,const vi& is) { int n=a.size(); for(int i:is) a.push_back(a[i]); a.erase(begin(a),begin(a)+n); } int solve(vi& hs,vi& as,vi& ds,vi& ss) { { vi is(1,0); repi(i,1,hs.size()){ int a=max(as[0]-ds[i],0); // 与ダメージ int b=max(as[i]-ds[0],0); // 被ダメージ if(a==0) if(b==0); // 与・被ダメージが0である敵はいなかったことにする else return -1; else is.push_back(i); } permute(hs,is); permute(as,is); permute(ds,is); permute(ss,is); } int n=hs.size(); vi ts(n); // 殺すために必要なターン数 vi ps(n); // 被ダメージ repi(i,1,n){ int dam=max(as[0]-ds[i],0); assert(dam>0); ts[i]=(hs[i]+dam-1)/dam; ps[i]=max(as[i]-ds[0],0); } ll dam=0; // 自分の最初のターン目までの被ダメージ repi(i,1,n) if(ss[i]>ss[0]) dam+=ps[i]; { vi is(n); iota(all(is),0); sort(all(is),[&](int i,int j){return ss[i]>ss[j];}); permute(ts,is); permute(ps,is); rep(i,n) if(is[i]==0){ rotate(begin(ts),begin(ts)+i+1,end(ts)); ts.pop_back(); rotate(begin(ps),begin(ps)+i+1,end(ps)); ps.pop_back(); n--; break; } } ll h=hs[0]; { vi is(n); iota(all(is),0); sort(all(is),[&](int i,int j){return ll(ts[i])*(ps[j])<ll(ts[j])*(ps[i]);}); permute(ts,is); permute(ps,is); } vl sum(n+1); per(i,n) sum[i]=sum[i+1]+ps[i]; bool ok=true; rep(i,n){ if(h<=dam+1.*ts[i]*sum[i]-ps[i]){ ok=false; break; } dam+=ll(ts[i])*sum[i]-ps[i]; } return ok?dam:-1; } int main() { for(int n;cin>>n && n;){ vi hs(n+1),as(n+1),ds(n+1),ss(n+1); rep(i,n+1) cin>>hs[i]>>as[i]>>ds[i]>>ss[i]; cout<<solve(hs,as,ds,ss)<<endl; } }
#include <iostream> #include <vector> #include <algorithm> #include <tuple> #include <cmath> using namespace std; typedef tuple<double,int64_t,int64_t> T;// ??????/????????????????????°, ??????, ???????????° int main(){ int N; cin>>N; vector<int64_t> H(N+1), A(N+1), D(N+1), S(N+1); for(int i=0;i<=N;i++){ cin>>H[i]>>A[i]>>D[i]>>S[i]; } int64_t damage = 0, firepower = 0; vector<T> V; for(int i=1;i<=N;i++){ int64_t fire=max(A[i]-D[0],int64_t(0)); if(S[i]>S[0])damage+=fire; firepower+=fire; if(max(A[0]-D[i],int64_t(0))==0&&max(A[i]-D[0],int64_t(0))){ cout<<-1<<endl; return 0; } int64_t turns=ceil(double(H[i])/(max(A[0]-D[i],int64_t(0)))); V.emplace_back(double(fire)/turns,fire,turns); } sort(V.begin(), V.end(),greater<T>()); for(auto t:V){ int64_t fire,turns; tie(ignore,fire,turns)=t; //cout<<fire<<' '<<turns<<endl; damage+=firepower*(turns-1); firepower-=fire; damage+=firepower; if(damage>=H[0]){ cout<<-1<<endl; return 0; } } cout<<damage<<endl; }
#include<bits/stdc++.h> using namespace std; using ll=long long; int main(){ int n; cin>>n; ll ph,pa,pd,ps; vector<ll> h(n),a(n),d(n),s(n); cin>>ph>>pa>>pd>>ps; for(int i=0;i<n;i++){ cin>>h[i]>>a[i]>>d[i]>>s[i]; } vector<ll> t(n); bool poyo=false; for(int i=0;i<n;i++){ if(d[i]>=pa){ if(a[i]-pd<=0){ poyo=true; t[i]=1; } else{ cout<<-1<<endl; return 0; } } else{ t[i]=h[i]/(pa-d[i])+(int)(h[i]%(pa-d[i])>0); } } vector<int> idx(n); iota(idx.begin(),idx.end(),0); auto cmp=[&](int lhs,int rhs){return (a[lhs]-pd)*t[rhs]>(a[rhs]-pd)*t[lhs];}; sort(idx.begin(),idx.end(),cmp); ll dmg=0; for(int i=0;i<n;i++){ if(s[i]>ps){ dmg+=max(a[i]-pd,0LL); } } ll sumt=0; for(int i=0;i<n;i++){ int id=idx[i]; sumt+=t[id]; if(sumt-1>=1e9+1 && a[id]-pd>0){ cout<<-1<<endl; return 0; } dmg+=max(a[id]-pd,0LL)*(sumt-1); if(dmg>=ph){ cout<<-1<<endl; return 0; } } if(dmg<ph){ cout<<dmg<<endl; } else{ cout<<-1<<endl; } return 0; }
#include <bits/stdc++.h> #define N 40001 using namespace std; typedef long long ll; struct po{ll h,a,d,s;}; ll n; po A[N]; ll hp,a,d,s,sum; bool compare(po x,po y){ if(a-x.d<=0||a-y.d<=0)return 0; ll cnt1=1+(x.h-1)/(a-x.d),cnt2=1+(y.h-1)/(a-y.d); ll X=cnt1*(x.a-d)+(cnt1+cnt2)*(y.a-d); ll Y=cnt2*(y.a-d)+(cnt1+cnt2)*(x.a-d); return X<Y; } ll solve(){ sort(A,A+n,compare); for(int i=0;i<n;i++){ po t=A[i]; if(hp<=0)return -1; if(a-t.d<=0) return -1; ll cost=((t.h-1)/(a-t.d))*sum; sum-=t.a-d; hp-=(cost+sum); } if(hp<=0)return -1; return hp; } int main(){ cin>>n; cin>>hp>>a>>d>>s; ll ofs=0; for(int i=0;i<n;i++){ po &t=A[i]; cin>>t.h>>t.a>>t.d>>t.s; if(t.a-d<=0){n--,i--;continue;}; if(t.s>s) ofs+=(t.a-d); sum+=(t.a-d); } ll H = hp; hp-=ofs; ll ans= H-solve(); if(H<ans)cout<<-1<<endl; else cout<<ans<<endl; return 0; }
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) struct Enemy { ll cnt; ll attack; int after; Enemy() {;} Enemy(ll cnt, ll attack, int after) : cnt(cnt), attack(attack), after(after) {;} bool operator<(const Enemy &rhs) const { return rhs.cnt * attack < cnt * rhs.attack; } }; int n; ll h, a, d, s; int main() { while (scanf("%d", &n) > 0) { scanf("%lld %lld %lld %lld", &h, &a, &d, &s); ll attackSum = 0; vector<Enemy> enemys; bool ng = false; REP(i, n) { ll eh, ea, ed, es; scanf("%lld %lld %lld %lld", &eh, &ea, &ed, &es); ll attack = ea - d; ll damage = a - ed; if (attack <= 0) { continue; } if (damage <= 0) { ng = true; continue; } ll cnt = (eh + damage - 1) / damage; int after = 0; if (es < s) { after = 1; } attackSum += attack; enemys.push_back(Enemy(cnt, attack, after)); } if (ng) { puts("-1"); continue; } ll ans = 0; sort(enemys.rbegin(), enemys.rend()); FORIT(it, enemys) { attackSum -= it->attack; ans += attackSum * it->cnt; ll cnt = it->cnt; if (it->after) { cnt--; } ans += it->attack * cnt; if (ans >= h) { break; } } if (h <= ans) { puts("-1"); } else { printf("%lld\n", ans); } } }
#include <algorithm> #include <iostream> #include <vector> #include <utility> using namespace std; int main(){ int N; cin >> N; long long int H[N], A[N], D[N], S[N], h, a, d, s, t, ans = 0LL; cin >> h >> a >> d >> s; for(int i = 0; i < N; ++i){ cin >> H[i] >> A[i] >> D[i] >> S[i]; A[i] -= d; A[i] = max(A[i],0LL); if(S[i] < s) ans -= A[i]; } vector< pair<double, int> > V; for(int i = 0; i < N; ++i){ if(a <= D[i] && A[i] > 0){ cout << -1 << endl; return 0; } if(a > D[i]){ t = (H[i]+a-D[i]-1)/(a-D[i]); V.push_back(make_pair(-(double)A[i]/t,i)); }else{//A[i] == 0 && a == D[i] V.push_back(make_pair(0,i)); } } sort(V.begin(),V.end()); t = 0LL; for(int i = 0; i < N; ++i){ //cout << V[i].first << " " << V[i].second << endl; int j = V[i].second; if(a != D[j]){ t += (H[j]+a-D[j]-1)/(a-D[j]); } ans += t*A[j]; //cout << t << " " << ans << endl; if(ans >= h){ cout << -1 << endl; return 0; } } if(ans >= h) cout << -1 << endl; else cout << ans << endl; return 0; }
#include <bits/stdc++.h> #define ll long long #define INF 1000000005 #define MOD 1000000007 #define EPS 1e-10 #define rep(i,n) for(int i=0;i<(int)(n);++i) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i) #define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i) #define each(a,b) for(auto (a): (b)) #define all(v) (v).begin(),(v).end() #define len(v) (int)(v).size() #define zip(v) sort(all(v)),v.erase(unique(all(v)),v.end()) #define cmx(x,y) x=max(x,y) #define cmn(x,y) x=min(x,y) #define fi first #define se second #define pb push_back #define show(x) cout<<#x<<" = "<<(x)<<endl #define spair(p) cout<<#p<<": "<<p.fi<<" "<<p.se<<endl #define svec(v) cout<<#v<<":";rep(kbrni,v.size())cout<<" "<<v[kbrni];cout<<endl #define sset(s) cout<<#s<<":";each(kbrni,s)cout<<" "<<kbrni;cout<<endl #define smap(m) cout<<#m<<":";each(kbrni,m)cout<<" {"<<kbrni.first<<":"<<kbrni.second<<"}";cout<<endl #define int long long using namespace std; typedef pair<int,int> P; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<double> vd; typedef vector<P> vp; typedef vector<string> vs; const int MAX_N = 100005; struct data { int h,a,d,s,u,v; }; vector<data> vec; data zibun; int n; bool possible(int cri) { int tm = 0; int al = 0; rep(i,len(vec)){ // cout << vec[i].h << " " << vec[i].a << " " << vec[i].d << " " << vec[i].s << " " << vec[i].u << " " << vec[i].v << "\n"; if(zibun.s > vec[i].s){ tm += vec[i].v - 1; al += tm*vec[i].u; ++tm; }else{ tm += vec[i].v; al += tm*vec[i].u; } if(al > cri){ return false; } } return true; } signed main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; rep(i,n+1){ int w,x,y,z; cin >> w >> x >> y >> z; if(i == 0){ zibun = (data){w,x,y,z,0LL,0LL}; }else{ if(zibun.a <= y){ if(zibun.d < x){ cout << "-1\n"; return 0; }else{ continue; } } vec.pb((data){w,x,y,z,max(x-zibun.d,0LL),(ll)floor((double)(w-0.5)/(zibun.a-y))+1LL}); } } sort(all(vec),[&](const data& x,const data& y){ return (y.u*x.v == x.u*y.v)?(x.s > y.s):(y.u*x.v < x.u*y.v); }); int l = 0,r = zibun.h-1; if(!possible(r)){ cout << "-1\n"; return 0; } if(possible(0)){ cout << "0\n"; return 0; } while(r-l>1){ int mid = (l+r)/2; if(possible(mid)){ r = mid; }else{ l = mid; } } cout << r << "\n"; return 0; }
#include <iostream> #include <vector> #include <algorithm> #define llint long long using namespace std; struct Data{ llint T, D; Data(){} Data(llint a, llint b){ T = a, D = b; } bool operator<(const Data& obj)const{ if(obj.D == 0) return D != 0; if(D == 0) return false; return (double)T/D < (double)obj.T/obj.D; } }; llint n; llint h[40005], a[40005], d[40005], s[40005]; vector<Data> vec; int main(void) { cin >> n; for(int i = 0; i <= n; i++) cin >> h[i] >> a[i] >> d[i] >> s[i]; bool pWin = true, mWin = false; for(int i = 1; i <= n; i++){ if(a[0] - d[i] <= 0 && a[i] - d[0] > 0){ pWin = false; break; } } if(!pWin){ cout << -1 << endl; return 0; } for(int i = 1; i <= n; i++){ if(a[0] - d[i] <= 0) continue; vec.push_back(Data( (h[i]+a[0]-d[i]-1)/(a[0]-d[i]), max(0LL, a[i] - d[0]) ) ); } sort(vec.begin(), vec.end()); llint ans = 0, sumT = 0; for(int i = 1; i <= n; i++){ if(s[0] > s[i]) ans -= max(0LL, a[i] - d[0]); } for(int i = 0; i < vec.size(); i++){ sumT += vec[i].T; ans += sumT * vec[i].D; if(ans >= h[0]){ cout << -1 << endl; return 0; } } if(ans >= h[0]) ans = -1; cout << ans << endl; return 0; }
#include <bits/stdc++.h> using namespace std; #define reep(i,a,b) for(int i=(a);i<(b);i++) #define rep(i,n) reep((i),0,(n)) typedef pair<int,int> pii; typedef pair<double,pii> P; typedef long long ll; #define mkp make_pair #define F first #define S second // #define int long long // struct P { // double first; // pii second; // P(double f, pii s) { // first = f; // second = s; // } // bool operator<(const P & obj) const { // return this->S.S * obj.S.F > this->S.F * obj.S.S; // } // }; signed main(){ int n; cin>>n; long long ans=0; n++; vector<int> h(n),a(n),d(n),s(n); rep(i,n) cin>>h[i]>>a[i]>>d[i]>>s[i]; reep(i,1,n){ a[i]=max(a[i]-d[0],0); } vector<int> atack(n); reep(i,1,n){ atack[i]=max(a[0]-d[i],0); } vector<P> v; reep(i,1,n){ if(a[i]==0){ continue; } if(s[i]>s[0]) ans+=a[i]; if(atack[i]==0){ puts("-1"); return 0; } int tmp=h[i]/atack[i]; if(h[i]%atack[i]) tmp++; // v.push_back(mkp( (double)a[i]/tmp, pii(a[i],tmp)) ); v.push_back(mkp( (double)a[i]/tmp, pii(a[i],tmp)) ); } sort(v.begin(),v.end()); reverse(v.begin(),v.end()); ll turn=0; rep(i,v.size()){ // acout << ans << endl; turn+=v[i].S.S; ans+=(turn-1LL)*v[i].S.F; if(ans>=h[0]){ puts("-1"); return 0; } } // if(ans>=(ll)h[0]) puts("-1"); cout<<ans<<endl; // rep(i,v.size()){ // cout<<v[i].F<<" "<<v[i].S.F<<" "<<v[i].S.S<<endl; // } // ll ans1=LLONG_MAX; // do{ // ll tmp=0; // turn=0; // rep(i,v.size()){ // turn+=v[i].S.S; // tmp+=(turn-1)*v[i].S.F; // } // ans1=min(ans1,tmp+ans); // }while(next_permutation(v.begin(),v.end())); // if(ans1!=ans){ // cout<<"NO"<<endl; // } }
#include<bits/stdc++.h> using namespace std; using Int = long long; signed main(){ Int n; cin>>n; n++; vector<Int> h(n),a(n),d(n),s(n); for(Int i=0;i<n;i++) cin>>h[i]>>a[i]>>d[i]>>s[i]; bool f=1; for(Int i=1;i<n;i++) if(d[0]-a[i]<=0) f=0; if(f){ cout<<0<<endl; return 0; } for(Int i=1;i<n;i++) if(a[0]-d[i]<=0&&a[i]-d[0]>0) f=1; if(f){ cout<<-1<<endl; return 0; } //cout<<"OOO"<<endl; auto get=[&](Int i,bool f=1){ Int k=a[0]-d[i]; if(k<=0) return 0LL; Int res=(h[i]+k-1)/k; if(f&&s[i]<s[0]) res--; return res; }; auto dm=[&](Int i){return max(a[i]-d[0],0LL);}; vector<Int> x(n-1); for(Int i=1;i<n;i++) x[i-1]=i; auto tmp=[&](Int p,Int q){return get(p)*dm(p)+(get(p,0)+get(q))*dm(q);}; //cout<<x.size()<<endl; sort(x.begin(),x.end(), [&](Int p,Int q){ //cout<<p<<" "<<q<<endl; //cout<<tmp(p,q)<<endl; //cout<<tmp(q,p)<<endl; if(dm(q)==0) return dm(p)!=0; return tmp(p,q)<tmp(q,p); }); Int t=0; Int ans=accumulate(x.begin(),x.end(),0LL, [&](Int res,Int y){ //cout<<res<<" "<<t<<":"<<y<<" "<<dm(y)<<endl; if(res>=h[0]) return res; res+=(t+get(y))*dm(y); t+=get(y,0); return res; }); if(ans>=h[0]) cout<<-1<<endl; else cout<<ans<<endl; return 0; }
#include <iostream> #include <vector> #include <algorithm> struct Character { int health; int attack; int defence; int speed; }; struct Enemy : public Character { bool defeatable; unsigned long long dameges_per_turn; unsigned long long turns_for_beat; Enemy() : defeatable(true) { } }; std::istream& operator>>(std::istream& stream, Character& character) { return ( stream >> character.health >> character.attack >> character.defence >> character.speed ); } int main() { // read length of enemies int enemy_length; std::cin >> enemy_length; // read player data Character player; std::cin >> player; // read enemies data std::vector<Enemy> enemies(enemy_length); for(auto& enemy : enemies) std::cin >> enemy; // calculate enemies extra data for(auto& enemy : enemies) { // calculate dameges int damage_for_enemy = player.attack - enemy .defence; int damage_for_player = enemy .attack - player.defence; // turns_for_beat if(damage_for_enemy <= 0) enemy.defeatable = false; else enemy.turns_for_beat = enemy.health / damage_for_enemy + (enemy.health % damage_for_enemy ? 1 : 0); // damages_per_turn enemy.dameges_per_turn = damage_for_player > 0 ? damage_for_player : 0; // cannot defeat this enemy no matter how if(!enemy.defeatable && enemy.dameges_per_turn > 0) { std::cout << -1 << std::endl; return 0; } } // erase immortal but harmless enemies enemies.erase( std::remove_if( enemies.begin(), enemies.end(), [](const Enemy& enemy) { return !(enemy.defeatable); } ), enemies.end() ); // sort enemies by order to defeat std::sort( enemies.begin(), enemies.end(), [](const Enemy& lhs, const Enemy& rhs) { return (rhs.dameges_per_turn * lhs.turns_for_beat) < (lhs.dameges_per_turn * rhs.turns_for_beat); } ); // surprise attack by enemy unsigned long long total_damages = 0; for(auto& enemy : enemies) if(player.speed < enemy.speed) total_damages += enemy.dameges_per_turn; // fight simulation unsigned long long total_turns = 0; for(auto& enemy : enemies) { total_turns += enemy.turns_for_beat; total_damages += enemy.dameges_per_turn * (total_turns - 1); // player lose test if(player.health <= total_damages) { std::cout << -1 << std::endl; return 0; } } // result std::cout << total_damages << std::endl; return 0; }
#include <iostream> #include <algorithm> #include <vector> using namespace std; typedef long long lli; const int MAXN = 40004; int n; lli h[MAXN], a[MAXN], d[MAXN], s[MAXN]; lli T(const int &e) { return (h[e]+(a[0]-d[e]-1))/(a[0]-d[e]); } bool comp(const int &e1, const int &e2) { return T(e1)*(a[e2]-d[0]) < T(e2)*(a[e1]-d[0]); } int main() { while(cin >> n) { ++n; for(int i = 0; i < n; ++i) { cin >> h[i] >> a[i] >> d[i] >> s[i]; } vector<int> id; bool lose = false; for(int i = 1; i < n; ++i) { if(a[i]-d[0] <= 0) { continue; } if(a[0]-d[i] <= 0) { lose = true; break; } id.push_back(i); } if(lose) { cout << -1 << endl; continue; } sort(id.begin(), id.end(), comp); lli damage = 0; lli turn = 0; for(int i = 0; i < id.size(); ++i) { int e = id[i]; turn += T(e); if(s[0] > s[e]) damage += (turn-1)*(a[e]-d[0]); else damage += turn*(a[e]-d[0]); damage = min(damage, h[0]); } if(h[0]-damage <= 0) cout << -1 << endl; else cout << damage << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) a.begin(), a.end() #define MS(m,v) memset(m,v,sizeof(m)) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<string> vs; typedef pair<int, int> pii; const int MOD = 1000000007; const int INF = MOD + 1; const ld EPS = 1e-12; template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); } template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); } /*--------------------template--------------------*/ int main() { cin.sync_with_stdio(false); cout << fixed << setprecision(10); int n; cin >> n; ll H, A, D, S; cin >> H >> A >> D >> S; ll ans = 0; vector<pii> v; REP(i, n) { ll h, a, d, s; cin >> h >> a >> d >> s; ll dmg = max(0ll, a - D); if (S > s) { H += dmg; ans -= dmg; } ll gdmg = max(0ll, A - d); if (dmg > 0 && gdmg == 0) { cout << -1 << endl; return 0; } if (dmg == 0) continue; v.emplace_back((h + gdmg - 1) / gdmg, dmg); } sort(ALL(v), [](const pii& a, const pii& b) {return (ld)a.first / a.second < (ld)b.first / b.second; }); ll sum = 0; REP(i, v.size()) { sum += v[i].first; ans += sum * v[i].second; if (ans >= H) { cout << -1 << endl; return 0; } } cout << ans << endl; return 0; }
#include <iostream> #include <fstream> #include <cassert> #include <typeinfo> #include <vector> #include <stack> #include <cmath> #include <set> #include <map> #include <string> #include <algorithm> #include <cstdio> #include <queue> #include <iomanip> #include <cctype> #include <random> #include <complex> #define syosu(x) fixed<<setprecision(x) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> P; typedef pair<double,double> pdd; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<char> vc; typedef vector<vc> vvc; typedef vector<string> vs; typedef vector<bool> vb; typedef vector<vb> vvb; typedef vector<P> vp; typedef vector<vp> vvp; typedef vector<pll> vpll; typedef pair<P,int> pip; typedef vector<pip> vip; const int inf=1<<28; const ll INF=1ll<<60; const double pi=acos(-1); const double eps=1e-8; const ll mod=1e9+7; const int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0}; ll n,H,A,D,S; vl h,a; int main(){ cin>>n>>H>>A>>D>>S; ll res=H,as=0; h=a=vl(n); vector<pair<double,int> > b; for(int i=0;i<n;i++){ ll d,s; cin>>h[i]>>a[i]>>d>>s; a[i]=max(a[i]-D,0ll); as+=a[i]; if(A<=d&&a[i]){ cout<<-1<<endl; return 0; } if(A-d>0){ ll da=A-d; h[i]=(h[i]+da-1)/da; if(s>S) res-=a[i]; if(a[i]){ b.push_back({(double)h[i]/a[i],i}); } } } sort(b.begin(),b.end()); int B=b.size(); for(int i=0;i<B;i++){ int I=b[i].second; if(res<as-a[I]){ cout<<-1<<endl; return 0; } res-=as*h[I]-a[I]; as-=a[I]; if(res<=0){ cout<<-1<<endl; return 0; } } cout<<H-res<<endl; }
#include <vector> #include <iostream> #include <utility> #include <algorithm> #include <string> #include <deque> #include <tuple> #include <queue> #include <functional> #include <cmath> #include <iomanip> #include <map> #include <numeric> #include <unordered_map> #include <unordered_set> #include <complex> #include <iterator> #include <array> #include <chrono> //cin.sync_with_stdio(false); //streambuf using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<double, double> pdd; using vi = vector<int>; using vll = vector<ll>; using vpii = vector<pii>; template<class T, int s>using va = vector<array<T, s>>; template<class T, class T2> using umap = unordered_map<T, T2>; template<class T> using uset = unordered_set<T>; template<class T, class S> void cmin(T &a, const S&&b) { if (a > b)a = b; } template<class T, class S> void cmax(T &a, const S&&b) { if (a < b)a = b; } #define ALL(a) a.begin(),a.end() #define rep(i,a) for(int i=0;i<a;i++) #define rep1(i,a) for(int i=1;i<=a;i++) #define rrep(i,a) for(int i=a-1;i>=0;i--) #define rrep1(i,a) for(int i=a;i;i--) const ll mod = 1000000007; #ifndef INT_MAX const int INT_MAX = numeric_limits<signed>().max(); #endif template<class T>using heap = priority_queue<T, vector<T>, greater<T>>; template<class T>using pque = priority_queue<T, vector<T>, function<T(T, T)>>; template <class T> inline void hash_combine(size_t & seed, const T & v) { hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; hash_combine(seed, v.first); hash_combine(seed, v.second); return seed; } }; // Recursive template code derived from Matthieu M. template <class Tuple, size_t Index = std::tuple_size<Tuple>::value - 1> struct HashValueImpl { static void apply(size_t& seed, Tuple const& tuple) { HashValueImpl<Tuple, Index - 1>::apply(seed, tuple); hash_combine(seed, std::get<Index>(tuple)); } }; template <class Tuple> struct HashValueImpl<Tuple, 0> { static void apply(size_t& seed, Tuple const& tuple) { hash_combine(seed, std::get<0>(tuple)); } }; template <typename ... TT> struct hash<std::tuple<TT...>> { size_t operator()(std::tuple<TT...> const& tt) const { size_t seed = 0; HashValueImpl<std::tuple<TT...> >::apply(seed, tt); return seed; } }; } ll pow(ll base, ll i, ll mod) { ll a = 1; while (i) { if (i & 1) { a *= base; a %= mod; } base *= base; base %= mod; i /= 2; } return a; } class unionfind { vector<int> par, rank, size_;//????????§??????????????¢???????????????????????????rank???????????????size????????? public: unionfind(int n) :par(n), rank(n), size_(n, 1) { iota(ALL(par), 0); } int find(int x) { if (par[x] == x)return x; return par[x] = find(par[x]); } void unite(int x, int y) { x = find(x), y = find(y); if (x == y)return; if (rank[x] < rank[y])swap(x, y); par[y] = x; size_[x] += size_[y]; if (rank[x] == rank[y])rank[x]++; } bool same(int x, int y) { return find(x) == find(y); } int size(int x) { return size_[find(x)]; } }; ll gcd(ll a, ll b) { while (b) { ll c = a%b; a = b; b = c; } return a; } ll lcm(ll a, ll b) { return a / gcd(a, b)*b; } int popcnt(unsigned long long a) { a = (a & 0x5555555555555555) + (a >> 1 & 0x5555555555555555); a = (a & 0x3333333333333333) + (a >> 2 & 0x3333333333333333); a = (a & 0x0f0f0f0f0f0f0f0f) + (a >> 4 & 0x0f0f0f0f0f0f0f0f); a = (a & 0x00ff00ff00ff00ff) + (a >> 8 & 0x00ff00ff00ff00ff); a = (a & 0x0000ffff0000ffff) + (a >> 16 & 0x0000ffff0000ffff); return (a & 0xffffffff) + (a >> 32); } template<class T, class Func = function<T(T, T)>> class segtree { vector<T> obj; int offset; Func updater; T e; int bufsize(int num) { int i = 1; for (; num >i; i <<= 1); offset = i - 1; return (i << 1) - 1; } T query(int a, int b, int k, int l, int r) { if (r <= a || b <= l)return e; if (a <= l && r <= b)return obj[k]; else return updater(query(a, b, k * 2 + 1, l, (l + r) / 2), query(a, b, k * 2 + 2, (l + r) / 2, r)); } public: T query(int a, int b) {//[a,b) return query(a, b, 0, 0, offset + 1); } void updateall(int l = 0, int r = -1) { if (r < 0)r = offset + 1; l += offset, r += offset; do { l = l - 1 >> 1, r = r - 1 >> 1; for (int i = l; i < r; i++)obj[i] = updater(obj[i * 2 + 1], obj[i * 2 + 2]); } while (l); } void update(int k, T &a) { k += offset; obj[k] = a; while (k) { k = k - 1 >> 1; obj[k] = updater(obj[k * 2 + 1], obj[k * 2 + 2]); } } segtree(int n, T e, const Func &updater_ = Func()) :obj(bufsize(n), e), e(e), updater(updater_) {} segtree(vector<T> &vec, T e, const Func &updater = Func()) :obj(bufsize(vec.size()), e), e(e), updater(updater) { copy(vec.begin(), vec.end(), obj.begin() + offset); updateall(); } typename vector<T>::reference operator[](int n) { return obj[n + offset]; } }; template<class T> class matrix { vector<vector<T>> obj; pair<int, int> s; public: matrix(pair<int, int> size, T e = 0) :matrix(size.first, size.second, e) {} matrix(int n, int m = -1, T e = 0) :obj(n, vector<T>(m == -1 ? n : m, e)), s(n, m == -1 ? n : m) {} static matrix e(int n) { matrix a = (n); for (int i = 0; i < n; i++)a[i][i] = 1; return a; } matrix& operator+=(const matrix &p) { if (s != p.s)throw runtime_error("matrix error"); for (int i = 0; i < s.first; i++) for (int j = 0; j < s.second; j++)obj[i][j] += p.obj[i][j]; return *this; } matrix operator+(const matrix &p) { matrix res(*this); return res += p; } matrix& operator-=(const matrix &p) { if (s != p.s)throw runtime_error("matrix error"); for (int i = 0; i < s.first; i++) for (int j = 0; j < s.second; j++)obj[i][j] -= p.obj[i][j]; return *this; } matrix operator-(const matrix &p) { matrix res(*this); return res -= p; } matrix& operator*=(T p) { for (auto &a : obj) for (auto &b : a)b *= p; return *this; } matrix operator*(T p) { matrix res(*this); return res *= p; } matrix operator*(const matrix &p) { if (s.second != p.s.first)throw runtime_error("matrix error"); matrix ret(s.first, p.s.second); for (int i = 0; i < s.first; i++) for (int j = 0; j < s.second; j++) for (int k = 0; k < p.s.second; k++)ret[i][k] += obj[i][j] * p.obj[j][k]; return ret; } matrix &operator*=(const matrix &p) { return *this = *this*p; } pair<int, int> size() const { return s; } matrix &mod(T m) { for (auto &a : obj) for (auto &b : a)b %= m; return *this; } typename vector<vector<T>>::reference operator[](int t) { return obj[t]; } }; template<class T> inline matrix<T> pow(matrix<T> &base, unsigned exp) { auto base_(base); if (base_.size().first != base_.size().second)throw runtime_error("matrix error"); matrix<T> res = matrix<T>::e(base_.size().first); for (;;) { if (exp & 1)res *= base_; if (!(exp /= 2))break; base_ *= base_; } return res; } template<class T> inline matrix<T> modpow(matrix<T> &base, unsigned exp, T m) { auto base_(base); if (base.size().first != base_.size().second)throw runtime_error("matrix error"); matrix<T> res = matrix<T>::e(base_.size().first); for (;;) { if (exp & 1)(res *= base_).mod(m); if (!(exp /= 2))break; (base_ *= base_).mod(m); } return res; } template<class T>int id(vector<T> &a, T b) { return lower_bound(ALL(a), b) - a.begin(); } class Flow { int V; struct edge { int to, cap, rev, cost; }; vector<vector<edge>> G; vector<int> level, iter, h, dist, prevv, preve; public: Flow(int size) :G(size + 1), V(size + 1) { } void add_edge(int from, int to, int cap, int cost = 0) { G[from].push_back(edge{ to, cap, (int)G[to].size(),cost }); G[to].push_back(edge{ from,0,(int)G[from].size() - 1,-cost }); } void bfs(int s) { fill(level.begin(), level.end(), -1); queue<int> que; level[s] = 0; que.push(s); while (!que.empty()) { int v = que.front(); que.pop(); for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && level[e.to] < 0) { level[e.to] = level[v] + 1; que.push(e.to); } } } } int dfs(int v, int t, int f) { if (v == t)return f; for (int &i = iter[v]; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && level[v] < level[e.to]) { int d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } int max_flow(int s, int t) { level.resize(V); iter.resize(V); int flow = 0; for (;;) { bfs(s); if (level[t] < 0)return flow; fill(iter.begin(), iter.end(), 0); int f; while ((f = dfs(s, t, numeric_limits<int>::max()))>0) { flow += f; } } } typedef pair<int, int> P; int min_cost_flow(int s, int t, int f) { int res = 0; h.resize(V); dist.resize(V); prevv.resize(V); preve.resize(V); fill(h.begin(), h.end(), 0); while (f > 0) { priority_queue<P, vector<P>, greater<P>> que; fill(dist.begin(), dist.end(), numeric_limits<int>::max()); dist[s] = 0; que.push({ 0,s }); while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if (dist[v] < p.first)continue; for (int i = 0; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to]>dist[v] + e.cost + h[v] - h[e.to]) { dist[e.to] = dist[v] + e.cost + h[v] - h[e.to]; prevv[e.to] = v; preve[e.to] = i; que.push({ dist[e.to],e.to }); } } } if (dist[t] == numeric_limits<int>::max()) { return -1; } for (int v = 0; v < V; v++)h[v] += dist[v]; int d = f; for (int v = t; v != s; v = prevv[v]) { d = min(d, G[prevv[v]][preve[v]].cap); } f -= d; res += d*h[t]; for (int v = t; v != s; v = prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; const ld eps = 1e-11, pi = acos(-1.0); typedef complex<ld> P; typedef vector<P> VP; ld dot(P a, P b) { return real(conj(a) * b); } ld cross(P a, P b) { return imag(conj(a) * b); } namespace std { bool operator<(const P &a, const P &b) { return abs(a.real() - b.real()) < eps ? a.imag() < b.imag() : a.real() < b.real(); } } struct L { P a, b; };//line->l,segment->s struct C { P p; ld r; }; int ccw(P a, P b, P c) { b -= a; c -= a; if (cross(b, c) > eps) return 1; // counter clockwise if (cross(b, c) < -eps) return -1; // clockwise if (dot(b, c) < 0) return 2; // c--a--b on line if (norm(b) < norm(c)) return -2; // a--b--c on line return 0; // a--c--b on line } bool isis_ll(L l, L m) {//is intersect return abs(cross(l.b - l.a, m.b - m.a)) > eps; } bool isis_ls(L l, L s) { ld a = cross(l.b - l.a, s.a - l.a); ld b = cross(l.b - l.a, s.b - l.a); return (a * b < eps); } bool isis_lp(L l, P p) { return abs(cross(l.b - p, l.a - p)) < eps; } bool isis_ss(L s, L t) { return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0; } P is_ll(L s, L t) { //intersect P sv = s.b - s.a, tv = t.b - t.a; return s.a + sv * cross(tv, t.a - s.a) / cross(tv, sv); } bool isis_sp(L s, P p) { return abs(s.a - p) + abs(s.b - p) - abs(s.b - s.a) < eps; } P proj(L l, P p) { ld t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b); return l.a + t * (l.a - l.b); } ld dist_lp(L l, P p) { return abs(p - proj(l, p)); } ld dist_ll(L l, L m) { return isis_ll(l, m) ? 0 : dist_lp(l, m.a); } ld dist_ls(L l, L s) { if (isis_ls(l, s)) return 0; return min(dist_lp(l, s.a), dist_lp(l, s.b)); } ld dist_sp(L s, P p) { P r = proj(s, p); if (isis_sp(s, r)) return abs(r - p); return min(abs(s.a - p), abs(s.b - p)); } ld dist_ss(L s, L t) { if (isis_ss(s, t)) return 0; ld a = min(dist_sp(s, t.a), dist_sp(t, s.a)); ld b = min(dist_sp(s, t.b), dist_sp(t, s.b)); return min(a, b); } VP is_cc(C c1, C c2) { VP res; ld d = abs(c1.p - c2.p); ld rc = (d * d + c1.r * c1.r - c2.r * c2.r) / (2 * d); ld dfr = c1.r * c1.r - rc * rc; if (abs(dfr) < eps) dfr = 0.0; else if (dfr < 0.0) return res; // no intersection ld rs = sqrt(dfr); P diff = (c2.p - c1.p) / d; res.push_back(c1.p + diff * P(rc, rs)); if (dfr != 0.0) res.push_back(c1.p + diff * P(rc, -rs)); return res; } bool isis_vc(vector<C> vc) { VP crs; int n = vc.size(); rep(i, n)rep(j, i) for (P p : is_cc(vc[i], vc[j])) crs.push_back(p); rep(i, n) crs.push_back(vc[i].p); for (P p : crs) { bool valid = true; rep(i, n) if (abs(p - vc[i].p)>vc[i].r + eps) valid = false; if (valid) return true; } return false; } VP is_lc(C c, L l) { VP res; ld d = dist_lp(l, c.p); if (d < c.r + eps) { ld len = (d > c.r) ? 0.0 : sqrt(c.r * c.r - d * d); //safety; P nor = (l.a - l.b) / abs(l.a - l.b); res.push_back(proj(l, c.p) + len * nor); res.push_back(proj(l, c.p) - len * nor); } return res; } VP is_sc(C c, L l) { VP v = is_lc(c, l), res; for (P p : v) if (isis_sp(l, p)) res.push_back(p); return res; } vector<L> tangent_cp(C c, P p) {//????????\???? vector<L> ret; P v = c.p - p; ld d = abs(v); ld l = sqrt(norm(v) - c.r * c.r); if (isnan(l)) { return ret; } P v1 = v * P(l / d, c.r / d); P v2 = v * P(l / d, -c.r / d); ret.push_back(L{ p, p + v1 }); if (l < eps) return ret; ret.push_back(L{ p, p + v2 }); return ret; } vector<L> tangent_cc(C c1, C c2) { vector<L> ret; if (abs(c1.p - c2.p) - (c1.r + c2.r) > -eps) { P center = (c1.p * c2.r + c2.p * c1.r) / (c1.r + c2.r); ret = tangent_cp(c1, center); } if (abs(c1.r - c2.r) > eps) { P out = (-c1.p * c2.r + c2.p * c1.r) / (c1.r - c2.r); vector<L> nret = tangent_cp(c1, out); ret.insert(ret.end(), ALL(nret)); } else { P v = c2.p - c1.p; v /= abs(v); P q1 = c1.p + v * P(0, 1) * c1.r; P q2 = c1.p + v * P(0, -1) * c1.r; ret.push_back(L{ q1, q1 + v }); ret.push_back(L{ q2, q2 + v }); } return ret; } ld area(const VP &p) {//??¢????? ld res = 0; int n = p.size(); rep(j, n) res += cross(p[j], p[(j + 1) % n]); return res / 2; } bool is_polygon(L l, VP &g) { int n = g.size(); for (int i = 0; i < n; i++) { P a = g[i]; P b = g[(i + 1) % n]; if (isis_ss(l, L{ a, b })) return true; } return false; } int is_in_Polygon(const VP &g, P p) { bool in = false; int n = g.size(); for (int i = 0; i < n; i++) { P a = g[i] - p, b = g[(i + 1) % n] - p; if (imag(a) > imag(b)) swap(a, b); if (imag(a) <= 0 && 0 < imag(b)) if (cross(a, b) < 0) in = !in; if (abs(cross(a, b)) < eps && dot(a, b) < eps) return 0; // on } if (in) return 1; // in return -1; // out } VP ConvexHull(VP ps) { int n = ps.size(); int k = 0; sort(ps.begin(), ps.end()); VP ch(2 * n); for (int i = 0; i < n; ch[k++] = ps[i++]) while (k >= 2 && ccw(ch[k - 2], ch[k - 1], ps[i]) <= 0) --k; for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = ps[i--]) while (k >= t && ccw(ch[k - 2], ch[k - 1], ps[i]) <= 0) --k; ch.resize(k - 1); return ch; } VP ConvexCut(const VP &ps, L l) { VP Q; for (int i = 0; i < (int)ps.size(); i++) { P A = ps[i], B = ps[(i + 1) % ps.size()]; if (ccw(l.a, l.b, A) != -1) Q.push_back(A); if (ccw(l.a, l.b, A) * ccw(l.a, l.b, B) < 0) Q.push_back(is_ll(L{ A, B }, l)); } return Q; } double dist2(P a) { return real(a)*real(a) + imag(a)*imag(a); } // Suffix Array ?????????O(|S|log^2|S|), ????´¢O(|T|log|S|), ?????????????§????O(|S|) class StringSearch { const int n; string S; public: vector<int> sa, rank; StringSearch(const string &S_) :n(S_.size()), S(S_), sa(n + 1), rank(n + 1) { for (int i = 0; i <= n; i++) { sa[i] = i; rank[i] = i < n ? S[i] : -1; } vector<int> tmp(n + 1); for (int k = 1; k <= n; k *= 2) { auto Compare_SA = [=](int i, int j) { if (this->rank[i] != this->rank[j]) return this->rank[i] < this->rank[j]; int ri = i + k <= n ? this->rank[i + k] : -1; int rj = j + k <= n ? this->rank[j + k] : -1; return ri < rj; }; sort(sa.begin(), sa.end(), Compare_SA); tmp[sa[0]] = 0; for (int i = 1; i <= n; i++) { tmp[sa[i]] = tmp[sa[i - 1]] + (Compare_SA(sa[i - 1], sa[i]) ? 1 : 0); } for (int i = 0; i <= n; i++) { this->rank[i] = tmp[i]; } } } bool Contain(const string &T) { int a = 0, b = n; while (b - a > 1) { int c = (a + b) / 2; if (S.compare(sa[c], T.length(), T) < 0) a = c; else b = c; } return S.compare(sa[b], T.length(), T) == 0; } vector<int> LCPArray() { for (int i = 0; i <= n; i++) rank[sa[i]] = i; int h = 0; vector<int> lcp(n + 1); for (int i = 0; i < n; i++) { int j = sa[rank[i] - 1]; if (h > 0) h--; for (; j + h < n && i + h < n; h++) { if (S[j + h] != S[i + h]) break; } lcp[rank[i] - 1] = h; } return lcp; } }; int main() { int n; cin >> n; array<int, 4> h; va<int, 4> o; rep(i, 4)cin >> h[i]; bool f = 0; rep(i, n) { array<int, 4> x; rep(j, 4)cin >> x[j]; if (h[1] <= x[2]) { if (x[1] <= h[2])continue; cout << -1 << endl; return 0; } else o.push_back(x); } n = o.size(); sort(ALL(o), [&h](array<int, 4> a, array<int, 4> b) { int at = (a[0] + h[1] - a[2] - 1) / (h[1] - a[2]), bt = (b[0] + h[1] - b[2] - 1) / (h[1] - b[2]); return(ll)(at + bt - (h[3] > b[3] ? 1 : 0))*max(b[1] - h[2], 0) + (ll)(at - (h[3] > a[3] ? 1 : 0))*max(a[1] - h[2], 0) < (ll)(bt - (h[3] > b[3] ? 1 : 0))*max(b[1] - h[2], 0) + (ll)(at + bt - (h[3] > a[3] ? 1 : 0))*max(a[1] - h[2], 0); }); ll ans = 0; ll turn = 0; rep(i, n) { turn += (o[i][0] + h[1] - o[i][2] - 1) / (h[1] - o[i][2]); ans += (ll)(turn - (h[3] > o[i][3] ? 1 : 0))*max(o[i][1] - h[2], 0); if (ans >= h[0])break; } cout << (h[0] <= ans ? -1 : ans) << endl; }
#include <bits/stdc++.h> using namespace std; #define rep(i,x,y) for(int i=(x);i<(y);++i) #define debug(x) #x << "=" << (x) #ifdef DEBUG #define _GLIBCXX_DEBUG #define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl #else #define print(x) #endif const int inf=1e9; const int64_t inf64=1e18; const double eps=1e-9; template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){ os << "["; for (const auto &v : vec) { os << v << ","; } os << "]"; return os; } void solve(){ int n; cin >> n; int64_t h,a,d,s; vector<int64_t> hs,as,ds,ss; vector<pair<int64_t,int64_t>> ps; vector<int> idx; cin >> h >> a >> d >> s; rep(i,0,n){ int64_t h_,a_,d_,s_; cin >> h_ >> a_ >> d_ >> s_; if(a-d_<=0){ if(a_-d>0){ cout << -1 << endl; return; } continue; } idx.push_back(idx.size()); ps.push_back(make_pair(max(a_-d,int64_t(0)),(h_+a-d_-1)/(a-d_)-(s_<s?1:0))); hs.push_back(h_); as.push_back(a_); ds.push_back(d_); ss.push_back(s_); } sort(idx.begin(),idx.end(),[&](int i,int j){ if(a-ds[i]<=0) return true; if(a-ds[j]<=0) return false; return ps[j].first*((hs[i]+a-ds[i]-1)/(a-ds[i]))> ps[i].first*((hs[j]+a-ds[j]-1)/(a-ds[j])); }); int64_t ans=0,sum=0; for(int i:idx){ ans+=ps[i].first*ps[i].second+sum*((hs[i]+a-ds[i]-1)/(a-ds[i])); sum+=ps[i].first; if(ans>=h){ cout << -1 << endl; return; } } cout << ans << endl; } int main(){ std::cin.tie(0); std::ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(10); solve(); return 0; }
#include <bits/stdc++.h> #define int long long using namespace std; const int INF = 1e9; inline int divceil(int x,int y){ return (y > 0 ? (x + y - 1) / y : INF); } signed main(){ int n,h[40010],a[40010],d[40010],s[40010]; cin >> n; for(int i = 0;i <= n;i++){ cin >> h[i] >> a[i] >> d[i] >> s[i]; } int ans = 0,sum = 0; for(int i = 1;i <= n;i++){ if(s[0] > s[i]) ans -= max(0ll,a[i] - d[0]); sum += max(0ll,a[i] - d[0]); } vector<int> vec(n); iota(vec.begin(),vec.end(),1); sort(vec.begin(),vec.end(),[&](int i,int j){ return divceil(h[i],a[0] - d[i]) * max(0ll,a[j] - d[0]) < divceil(h[j],a[0] - d[j]) * max(0ll,a[i] - d[0]); }); for(int v : vec){ ans += sum * divceil(h[v],a[0] - d[v]); if(ans >= h[0]){ cout << -1 << endl; return 0; } sum -= max(0ll,a[v] - d[0]); } cout << ans << endl; }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} using pl = pair<ll,ll>; const ll INF = 100000000000LL; ll mul(ll x, ll y) { if(x==0 || y==0) return 0; // x*y>INF if(x>INF/y) return INF; return x*y; } ll solve() { int n; cin >>n; ll H,A,D,S; cin >>H >>A >>D >>S; vector<ll> h(n),a(n),d(n),s(n); rep(i,n) cin >>h[i] >>a[i] >>d[i] >>s[i]; ll ret = 0; vector<pl> e; rep(i,n) { ll damage = max(0LL, a[i]-D); ll dd = max(0LL, A-d[i]); if(damage>0 && dd==0) return -1; if(dd>0) { ll turn = (h[i]+dd-1)/dd; if(S>s[i]) ret -= damage; e.pb({damage,turn}); } } sort(all(e),[](const pl &l, const pl &r){ return l.fi*r.se > l.se*r.fi; }); ll T = 0; rep(i,e.size()) { T += e[i].se; ret += mul(e[i].fi,T); if(ret >= H) return -1; } return ret; } int main() { cout << solve() << endl; return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define INF 1e9 class monster{ public: long long int atk, SpellCounter; monster(){} monster(long long int atk_, int spell_) :atk(atk_), SpellCounter(spell_) {} }; int main(void){ int n; cin >> n; long long int hero_h, hero_a, hero_d, hero_s; cin >> hero_h >> hero_a >> hero_d >> hero_s; long long int orig_h = hero_h; long long int sum = 0; long long int input_h, input_a, input_d, input_s; vector<pair<double, int> > rate; vector<monster> enemy; for(int i = 0; i < n; i++){ cin >> input_h >> input_a >> input_d >> input_s; long long int attack = max(input_a - hero_d, 0LL); // ????????¬????????????????????£???????????????????????¬????????????????????£????????? if(input_s > hero_s){ hero_h -= attack; } long long int SpellCounter; // ????????????????????????????\´????????????????????¶?????? if(hero_a <= input_d){ if(attack > 0){ cout << -1 << endl; return 0; } attack = 0; SpellCounter = 1; } else{ sum += attack; SpellCounter = ((input_h - 1) / (hero_a - input_d)) + 1; } rate.push_back(make_pair(attack / (double)SpellCounter, enemy.size())); enemy.push_back(monster(attack, SpellCounter)); } sort(rate.begin(), rate.end()); reverse(rate.begin(), rate.end()); for(int i = 0; i < n; i++){ long long int sc = enemy[rate[i].second].SpellCounter - 1; hero_h -= sc * sum; sum -= enemy[rate[i].second].atk; hero_h -= sum; if(hero_h <= 0){ cout << -1 << endl; return 0; } } cout << orig_h - hero_h << endl; return 0; }
#include "bits/stdc++.h" using namespace std; using ll = long long; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; ll hp, atk, def, spd; cin >> hp >> atk >> def >> spd; vector<ll> h, a, d, s; for (int i = 0; i < n; i++) { ll htmp, atmp, dtmp, stmp; cin >> htmp >> atmp >> dtmp >> stmp; if (dtmp >= atk && atmp > def) { cout << -1 << endl; return 0; } if (atmp <= def) continue; atmp -= def; h.push_back(htmp); a.push_back(atmp); d.push_back(dtmp); s.push_back(stmp); } n = h.size(); vector<ll> turn(n); for (int i = 0; i < n; i++) { ll tmp = atk - d[i]; turn[i] = (h[i] - 1) / tmp + 1; } vector<int> idx(n); for (int i = 0; i < n; i++) idx[i] = i; sort(idx.begin(), idx.end(), [&](int i, int j) { return turn[i] * a[j] < turn[j] * a[i]; }); ll ret = 0, cnt = 0; for (auto i : idx) { hp -= cnt * a[i]; ret += cnt * a[i]; cnt += turn[i]; if (s[i] <= spd) turn[i]--; hp -= turn[i] * a[i]; ret += turn[i] * a[i]; if (hp <= 0) { cout << -1 << endl; return 0; } } cout << ret << endl; }
// BEGIN CUT HERE #ifdef _MSC_VER #include <iostream> #include <vector> #include <algorithm> #include <string> #include <sstream> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> #include <queue> #include <stack> #include <map> #include <set> #include <numeric> #include <cctype> #include <tuple> #include <array> #include <climits> #include <bitset> #include <cassert> #include <unordered_map> #include <agents.h> #else // END CUT HERE #include <bits/stdc++.h> // BEGIN CUT HERE #endif // END CUT HERE #define FOR(i, a, b) for(int i = (a); i < (int)(b); ++i) #define rep(i, n) FOR(i, 0, n) #define ALL(v) v.begin(), v.end() #define REV(v) v.rbegin(), v.rend() #define MEMSET(v, s) memset(v, s, sizeof(v)) #define UNIQUE(v) (v).erase(unique(ALL(v)), (v).end()) #define MP make_pair #define MT make_tuple using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> P; int main(){ int n; cin >> n; vector<int> h(n + 1), a(n + 1), d(n + 1), s(n + 1); rep(i, n + 1) cin >> h[i] >> a[i] >> d[i] >> s[i]; ll ans = 0; ll sum = 0; vector<pair<int, int>> e; FOR(i, 1, n + 1){ int dmg = a[i] - d[0]; if (dmg <= 0) continue; if (s[i] > s[0]) ans += dmg; if (d[i] >= a[0]){ cout << -1 << endl; return 0; } int x = a[0] - d[i]; int turn = (h[i] + x - 1) / x; e.push_back(MP(dmg, turn)); sum += dmg; } if (sum >= 2e9){ cout << -1 << endl; return 0; } sort(ALL(e), [](const pair<int, int> &lhs, const pair<int, int> &rhs){return 1.*lhs.second / lhs.first < 1.*rhs.second / rhs.first; }); for (auto p : e){ ans += sum*p.second - p.first; if (ans >= h[0]){ ans = -1; break; } sum -= p.first; } cout << ans << endl; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> l_l; typedef pair<int, int> i_i; template<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; } struct enemy { ll time, damage; enemy(ll _time, ll _damage) { time = _time; damage = _damage; } }; bool operator<(enemy a, enemy b) { return a.time * b.damage < b.time * a.damage; } const long double EPS = 1e-10; const long long INF = 1e18; const long double PI = acos(-1.0L); //const ll mod = 1000000007; ll N; ll h[40500], a[40500], d[40500], s[40500]; vector<enemy> v; ll Total; int main() { //cout.precision(10); cin.tie(0); ios::sync_with_stdio(false); cin >> N; for(int i = 0; i <= N; i++) { cin >> h[i] >> a[i] >> d[i] >> s[i]; } for(int i = 1; i <= N; i++) { ll damage = a[i] - d[0]; if(damage <= 0) continue; if(s[i] > s[0]) Total += damage; ll dam = a[0] - d[i]; if(dam <= 0) { cout << -1 << endl; return 0; } ll timer = (h[i] + dam - 1) / dam; v.emplace_back(timer, damage); } sort(v.begin(), v.end()); vector<ll> sum(v.size() + 1); for(int i = (int)v.size() - 1; i >= 0; i--) { sum[i] = sum[i+1] + v[i].damage; } for(int i = 0; i < v.size(); i++) { Total += (v[i].time - 1) * sum[i]; Total += sum[i+1]; if(Total >= h[0]) { cout << -1 << endl; return 0; } } cout << Total << endl; return 0; }
#include<bits/stdc++.h> using namespace std; const int M = 1000000007; struct enemy { long long damage, turn; enemy(long long damage, long long turn) : damage(damage), turn(turn) {} bool operator<(const enemy& o) const { return turn * o.damage < damage * o.turn; } }; int main() { int n; cin >> n; long long h, a, d, s; cin >> h >> a >> d >> s; long long ans = 0, sum = 0; vector<enemy> v; for (int i = 0; i < n; ++i) { long long hi, ai, di, si; cin >> hi >> ai >> di >> si; if (ai <= d) continue; if (di >= a) { cout << "-1\n"; return 0; } if (si > s) ans += ai - d; sum += ai - d; v.push_back(enemy(ai - d, (hi + a - di - 1) / (a - di))); } sort(v.begin(), v.end()); for (auto& i : v) { ans += sum * i.turn - i.damage; sum -= i.damage; if (ans >= h) { cout << "-1\n"; return 0; } } cout << ans << "\n"; return 0; }
#include <bits/stdc++.h> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) #define abs(a) max((a),-(a)) #define rep(i,n) for(int i=0;i<(int)(n);i++) #define repe(i,n) rep(i,(n)+1) #define per(i,n) for(int i=(int)(n)-1;i>=0;i--) #define pere(i,n) rep(i,(n)+1) #define all(x) (x).begin(),(x).end() #define SP <<" "<< #define RET return 0 #define MOD 1000000007 #define INF 1000000000000000000 typedef long long LL; typedef long double LD; int main(){ int n; cin >> n; LL h,a,d,s; cin >> h >> a >> d >> s; vector<LL> eh(n),ea(n),ed(n),es(n); vector<pair<LD,LL>> ss(n,{0,-1}); LL ans=0; for(int i=0;i<n;i++){ cin >> eh[i] >> ea[i] >> ed[i] >> es[i]; ea[i]=max(ea[i]-d,0); ed[i]=max(a-ed[i],0); if(es[i]>s) ans+=ea[i]; if(ed[i]==0){ if(ea[i]>0){ cout << -1 << endl; return 0; } }else{ if(ea[i]==0) ss[i]={INF,i}; else ss[i]={((eh[i]+ed[i]-1)/ed[i])/(LD)ea[i],i}; } } sort(all(ss)); LL turn=0; int id; // cout << ans << endl; for(int i=0;i<n;i++){ if(ss[i].second!=-1){ id=ss[i].second; turn+=(eh[id]+ed[id]-1)/ed[id]; ans+=(turn-1)*ea[id]; // cout << id SP turn SP ans << endl; if(ans>=h){ cout << -1 << endl; return 0; } } } cout << ans << endl; return 0; }
#include<stdio.h> #include<algorithm> using namespace std; int b[41000]; int c[41000]; int d[41000]; int e[41000]; struct wolf{ int p,q; wolf(){} wolf(int A,int B){ p=A;q=B; } }; inline bool operator<(const wolf&a,const wolf&b){ return (long long)a.p*b.q<(long long)a.q*b.p; } wolf t[41000]; int main(){ int a;scanf("%d",&a); for(int i=0;i<a+1;i++)scanf("%d%d%d%d",b+i,c+i,d+i,e+i); long long ret=0; long long now=0; int n=0; for(int i=0;i<a;i++){ int p=max(c[i+1]-d[0],0); int r=max(c[0]-d[i+1],0); if(r==0&&p!=0){ printf("-1\n");return 0; }else if(r==0){ continue; } int q=(b[i+1]+r-1)/r; if(e[i+1]>e[0])ret+=p; t[n++]=wolf(q,p); now+=p; // printf("%d %d\n",p,q); } std::sort(t,t+n); ret-=now; for(int i=0;i<n;i++){ ret+=(long long)t[i].p*now; now-=t[i].q; if(ret>=b[0])break; } if(ret<b[0])printf("%lld\n",ret); else printf("-1\n"); }
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<complex> #include<bitset> #include<stack> #include<unordered_map> using namespace std; typedef long long ll; typedef unsigned int ui; const ll mod = 998244353; const ll INF = (ll)1000000007 * 1000000007; typedef pair<int, int> P; #define stop char nyaa;cin>>nyaa; #define rep(i,n) for(int i=0;i<n;i++) #define per(i,n) for(int i=n-1;i>=0;i--) #define Rep(i,sta,n) for(int i=sta;i<n;i++) #define rep1(i,n) for(int i=1;i<=n;i++) #define per1(i,n) for(int i=n;i>=1;i--) #define Rep1(i,sta,n) for(int i=sta;i<=n;i++) typedef long double ld; typedef complex<ld> Point; const ld eps = 1e-8; const ld pi = acos(-1.0); typedef pair<ll, ll> LP; typedef pair<ld, ld> LDP; int n; ll a[40001], t[40001]; ll H, A, D, S; typedef pair<ld, int> speP; vector<speP> v; int main() { cin >> n; ll ans = 0; cin >> H >> A >> D >> S; bool valid = true; rep(i, n) { ll h, d, s; cin >> h >> a[i] >> d >> s; a[i] = max(a[i] - D, (ll)0); if (s < S) { ans -= a[i]; } ll damage = A - d; if (damage <= 0&&a[i]>0) { valid = false; break; } else if (damage <= 0)continue; else { t[i] = (h + damage - 1) / damage; v.push_back({ a[i] / (ld)t[i], i }); } } if (!valid)cout << -1 << endl; else { sort(v.begin(), v.end(),greater<speP>()); ll sum = 0; rep(i, v.size()) { int id = v[i].second; sum += t[id]; ans += sum * a[id]; if (ans >= H)break; } if (ans >= H)cout << -1 << endl; else cout << ans << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int N; vector<int> H, A, D, S; typedef struct{ int turn, ad; }Enemy; bool operator < (const Enemy& l, const Enemy& r){ return l.turn * r.ad > r.turn * l.ad; } int solve(){ ll damage = 0; vector<bool> ignore(N, false); for(int i=1; i<=N; i++){ if(S[i] > S[0]) damage += max(0, A[i]-D[0]); if(D[i] >= A[0]){ if(A[i] > D[0]) return -1; else ignore[i] = true; } } vector<Enemy> enemies; for(int i=1; i<=N; i++) if(!ignore[i]){ int turn = (H[i]+A[0]-D[i]-1) / (A[0]-D[i]); Enemy enemy({turn, max(0, A[i]-D[0])}); enemies.push_back(enemy); } sort(enemies.begin(), enemies.end()); ll sd = 0; for(int i=0; i<enemies.size(); i++){ sd += enemies[i].ad; damage += sd * enemies[i].turn; damage -= enemies[i].ad; if(damage >= H[0]) return -1; } return damage; } int main(){ cin >> N; H.resize(N+1); A.resize(N+1); D.resize(N+1), S.resize(N+1); for(int i=0; i<=N; i++) cin >> H[i] >> A[i] >> D[i] >> S[i]; cout << solve() << endl; return 0; }
#include<cstdio> #include<algorithm> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; typedef long long ll; #define ceil(a,b) ((a+b-1)/(b)) struct enemy{ int c,d,s; // 倒すまでに叩くべき回数, 一回の攻撃で自分が受けるダメージ, 敏捷度 bool operator<(const enemy &e)const{ return (ll)c*e.d<(ll)d*e.c; } }; int main(){ int n; scanf("%d",&n); int h[40001],a[40001],d[40001],s[40001]; rep(i,n+1) scanf("%d%d%d%d",h+i,a+i,d+i,s+i); // 無敵の敵について例外処理 rep(i,n) if(a[0]<=d[i+1]) { if(d[0]<a[i+1]){ // 無敵の敵からダメージを受けるなら負けるしかない puts("-1"); return 0; } else{ // 無敵の敵からダメージを受けないならそんな敵はいないことにしてしまう swap(h[i+1],h[n]); swap(a[i+1],a[n]); swap(d[i+1],d[n]); swap(s[i+1],s[n]); n--; i--; } } int n_tmp=0; enemy E[40000]; rep(i,n){ if(a[i+1]<=d[0]) continue; E[n_tmp].c=ceil(h[i+1],a[0]-d[i+1]); E[n_tmp].d=a[i+1]-d[0]; E[n_tmp].s=s[i+1]; n_tmp++; } n=n_tmp; sort(E,E+n); ll dmg=0; // 1 ターン目に自分より速い敵の攻撃を受ける rep(i,n) if(s[0]<E[i].s) { dmg+=E[i].d; dmg=min(dmg,(ll)h[0]); } // しかるべき順で敵を倒したときの合計被ダメージを計算 ll c_sum=0; rep(i,n){ c_sum+=E[i].c; c_sum=min(c_sum,2000000000LL); dmg+=(c_sum-1)*E[i].d; dmg=min(dmg,(ll)h[0]); } if(h[0]<=dmg) puts("-1"); else printf("%lld\n",dmg); return 0; }
#include <iostream> #include <iomanip> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <complex> #include <cstring> #include <cstdlib> #include <cmath> #include <cassert> #include <climits> #include <queue> #include <set> #include <map> #include <valarray> #include <bitset> #include <stack> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() typedef long long ll; typedef pair<int,int> pii; const int INF = 1<<29; const double PI = acos(-1); const double EPS = 1e-8; typedef pair<ll,ll> pll; bool cmp(const pll &a, const pll &b) { return (ll)b.first*a.second < (ll)a.first*b.second; } int main() { ll n; cin >> n; vector<pll> v; ll h0,a0,d0,s0; cin >> h0 >> a0 >> d0 >> s0; ll hp = h0; ll sum = 0; REP(i,n) { ll h,a,d,s; cin >> h >> a >> d >> s; ll damage = max(a-d0, 0LL); ll attack = max(a0-d, 0LL); if (attack == 0) { if (damage) { cout << -1 << endl; return 0; } continue; } ll turn = (h + attack - 1) / attack; if (s0 < s) hp -= damage; v.push_back(pll(damage, turn)); sum += damage; } sort(ALL(v), cmp); REP(i,v.size()) { if (hp < 0) break; sum -= v[i].first; if (sum > hp/v[i].second) { hp = -1; break; } hp -= sum * v[i].second; hp -= v[i].first * (v[i].second - 1); } if (hp <= 0) cout << -1 << endl; else cout << h0-hp << endl; }
#include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; using ll = long long; struct Data { ll h, a, d, s; Data() {} Data(ll h, ll a, ll d, ll s) : h{h}, a{a}, d{d}, s{s} {} bool operator < (const Data& d) const { return s < d.s; } }; istream& operator >> (istream& is, Data& d) { return is >> d.h >> d.a >> d.d >> d.s; } ll solve(Data& M, vector<Data>& ene) { vector<pair<double, Data>> v; for (const Data& e : ene) { if (M.a <= e.d && M.d < e.a) return -1; ll turn = ceil((double)e.h / (M.a - e.d)); if (e.a - M.d <= 0) continue; v.emplace_back((double)(e.a - M.d) / turn, e); } sort(v.rbegin(), v.rend()); ll res = 0, total_turn = 0; for (const auto& d : v) { Data e = d.second; ll turn = ceil((double)e.h / (M.a - e.d)); total_turn += turn; ll damage = (total_turn - (M.s > e.s)) * max(0LL, e.a - M.d); M.h -= damage; if (M.h <= 0) return -1; res += damage; } return res; } int main() { int N; cin >> N; Data M; cin >> M; vector<Data> ene(N); for (int i = 0; i < N; i++) { cin >> ene[i]; } cout << solve(M, ene) << endl; return 0; }
#include <bits/stdc++.h> using namespace std; #define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define rep(i,n) repl(i,0,n) #define mp(a,b) make_pair((a),(b)) #define pb(a) push_back((a)) #define all(x) (x).begin(),(x).end() #define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x)) #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} #define INF 2147483600 long solve(){ int n; cin>>n; long ret=0; vector<long> h(n+1), a(n+1), d(n+1), s(n+1), t(n+1); rep(i,n+1) cin>>h[i]>>a[i]>>d[i]>>s[i]; repl(i,1,n+1){ long tmp = a[0]-d[i]; if(tmp<=0){ if(a[i]>d[0]) return -1; else tmp=1; } t[i] = (h[i]+tmp-1)/tmp; } // ?????´?????? ????????¬?????????????????? repl(i,1,n+1)if(s[0]>s[i]){ h[0] += max(a[i]-d[0], 0L); ret -= max(a[i]-d[0], 0L); } vector<int> vec(n); rep(i,n) vec[i]=i+1; sort(all(vec), [&](int i, int j){ long ia = max(a[i]-d[0],0L); long ja = max(a[j]-d[0],0L); return ia*t[j] > ja*t[i]; }); long acctime = 0; rep(i,n){ int id = vec[i]; acctime += t[id]; h[0] -= max(a[id]-d[0],0L) * acctime; ret += max(a[id]-d[0],0L) * acctime; if(h[0]<=0) return -1; } return ret; } int main(){ cout<<solve()<<endl; return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long int lli; struct info{ int h,a; double rate; info(int h, int a, double r):h(h), a(a), rate(r){} }; bool comp(const info& a, const info& b){ return a.rate > b.rate; } int main(){ int n; cin >> n; lli h,a,d,s; cin >> h >> a >> d >> s; vector<info> e; lli sum = 0, damage = 0; for(int i=0; i<n; i++){ int eh,ea,ed,es; cin >> eh >> ea >> ed >> es; ea -= d; if(ea <= 0) continue; if(es > s){ damage += ea; } if(a-ed <= 0){ h = 0; continue; } eh = (eh+(a-ed)-1)/(a-ed); e.push_back(info(eh, ea, (double)ea/eh)); sum += ea; } if(h==0){ cout << -1 << endl; return 0; } sort(e.begin(), e.end(), comp); for(int i=0; i<(int)e.size(); i++){ int limit = (h-damage)/sum; if(e[i].h > limit){ h=0; break; } damage += sum*(e[i].h-1); sum -= e[i].a; damage += sum; } if(h <= damage){ cout << -1 << endl; }else{ cout << damage << endl; } return 0; }
#include<cstdio> #include<algorithm> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; typedef long long ll; #define ceil(a,b) ((a+b-1)/(b)) struct enemy{ int c,d,s; // ツ倒ツつキツづ慊づ?づ可叩ツつュツづ猟つォツ嘉アツ青? ツ暗ェツ嘉アツづ個攻ツ個つづ?篠ゥツ閉ェツつェツ偲ウツつッツづゥツダツδ?ーツジ, ツ敏ツ渉キツ度 bool operator<(const enemy &e)const{ return (ll)c*e.d<(ll)d*e.c; } }; int main(){ int n; scanf("%d",&n); int h[40001],a[40001],d[40001],s[40001]; rep(i,n+1) scanf("%d%d%d%d",h+i,a+i,d+i,s+i); // ツ鳴ウツ敵ツづ個敵ツづ可づつつ「ツづ?療。ツ外ツ渉按猟? rep(i,n) if(a[0]<=d[i+1]) { if(d[0]<a[i+1]){ // ツ鳴ウツ敵ツづ個敵ツつゥツづァツダツδ?ーツジツづーツ偲ウツつッツづゥツづ按づァツ閉可つッツづゥツつオツつゥツづ按つ「 puts("-1"); return 0; } else{ // ツ鳴ウツ敵ツづ個敵ツつゥツづァツダツδ?ーツジツづーツ偲ウツつッツづ按つ「ツづ按づァツつサツづアツづ按敵ツづ債つ「ツづ按つ「ツつアツづ?づ可つオツづ?つオツづ慊つ、 swap(h[i+1],h[n]); swap(a[i+1],a[n]); swap(d[i+1],d[n]); swap(s[i+1],s[n]); n--; i--; } } int n_tmp=0; enemy E[40000]; rep(i,n){ if(a[i+1]<=d[0]) continue; E[n_tmp].c=ceil(h[i+1],a[0]-d[i+1]); E[n_tmp].d=a[i+1]-d[0]; E[n_tmp].s=s[i+1]; n_tmp++; } n=n_tmp; sort(E,E+n); ll dmg=0; // 1 ツタツーツδ督姪堋づ可篠ゥツ閉ェツづヲツづィツ堕ャツつ「ツ敵ツづ個攻ツ個つづーツ偲ウツつッツづゥ rep(i,n) if(s[0]<E[i].s) { dmg+=E[i].d; dmg=min(dmg,(ll)h[0]); } // ツつオツつゥツづゥツづ猟つォツ渉?づ?敵ツづーツ倒ツつオツつスツづ?つォツづ個債?計ツ氾ュツダツδ?ーツジツづーツ計ツ算 ll c_sum=0; rep(i,n){ c_sum+=E[i].c; c_sum=min(c_sum,2000000000LL); dmg+=(c_sum-1)*E[i].d; dmg=min(dmg,(ll)h[0]); } if(h[0]<=dmg) puts("-1"); else printf("%lld\n",dmg); return 0; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long int lli; struct info{ int h,a; double rate; info(int h, int a, double r):h(h), a(a), rate(r){} info(){} }; bool comp(const info& a, const info& b){ return a.rate > b.rate; } int main(){ int n; cin >> n; lli h,a,d,s; cin >> h >> a >> d >> s; vector<info> e(n); lli sum = 0, damage = 0; for(int i=0; i<n; i++){ int eh,ea,ed,es; cin >> eh >> ea >> ed >> es; ea -= d; if(ea <= 0){ e[i] = info(1, 0, 0); continue; } if(es > s){ damage += ea; } if(a-ed <= 0){ h = 0; continue; } eh = (eh+(a-ed)-1)/(a-ed); e[i] = info(eh, ea, (double)ea/eh); sum += ea; } if(h==0){ cout << -1 << endl; return 0; } sort(e.begin(), e.end(), comp); for(int i=0; sum>0; i++){ int limit = (h-damage)/sum; if(e[i].h > limit){ h=0; break; } damage += sum*(e[i].h-1); sum -= e[i].a; damage += sum; } if(h <= damage){ cout << -1 << endl; }else{ cout << damage << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; #define F first #define S second #define pi M_PI #define R cin>> #define Z class #define ll long long #define ln cout<<'\n' #define in(a) insert(a) #define pb(a) push_back(a) #define pd(a) printf("%.10f\n",a) #define mem(a) memset(a,0,sizeof(a)) #define all(c) (c).begin(),(c).end() #define iter(c) __typeof((c).begin()) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--) #define REP(i,m,n) for(int i=(int)(m);i<(int)(n);i++) #define rep(i,n) REP(i,0,n) #define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++) template<Z A>void pr(A a){cout<<a;ln;} template<Z A,Z B>void pr(A a,B b){cout<<a<<' ';pr(b);} template<Z A,Z B,Z C>void pr(A a,B b,C c){cout<<a<<' ';pr(b,c);} template<Z A,Z B,Z C,Z D>void pr(A a,B b,C c,D d){cout<<a<<' ';pr(b,c,d);} template<Z A>void PR(A a,ll n){rep(i,n){if(i)cout<<' ';cout<<a[i];}ln;} ll check(ll n,ll m,ll x,ll y){return x>=0&&x<n&&y>=0&&y<m;} const ll MAX=1000000007,MAXL=1LL<<61,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1}; typedef pair<ll,ll> P; bool cmp(P a,P b) { return a.F*b.S<b.F*a.S; } void Main() { ll n; R n; ll h[n+1],a[n+1],d[n+1],s[n+1]; rep(i,n+1) cin >> h[i] >> a[i] >> d[i] >> s[i]; ll ans=0,t=0; vector<P> v; REP(i,1,n+1) { ll x=a[i]-d[0],y=a[0]-d[i]; if(x<=0) continue; if(y<=0) { pr(-1); return; } if(s[0]<s[i]) ans+=x; t+=x; v.pb(P((ll)ceil((double)h[i]/y),x)); } sort(all(v),cmp); rep(i,v.size()) { ans+=t*v[i].F-v[i].S; if(ans>=h[0]) { pr(-1); return; } t-=v[i].S; } pr(ans); } int main(){ios::sync_with_stdio(0);cin.tie(0);Main();return 0;}
#include<iostream> #include<utility> #include<algorithm> using namespace std; int main(){ int n; cin>>n; int hh,ah,dh,sh; cin>>hh>>ah>>dh>>sh; pair<int,int> p[40000]; long long dmg=0; int INF=1<<30; long long dpt=0; for(int i=0;i<n;i++){ int h,a,d,s; cin>>h>>a>>d>>s; int of=max(0,a-dh); int df=max(0,ah-d); if(s>sh){ dmg+=of; if(dmg>=hh){ cout<<-1<<endl; return 0; } } dpt+=of; p[i]=make_pair(of,df?(h+df-1)/df:INF); } sort(p,p+n,[](pair<int,int> a,pair<int,int> b){ return a.first*1./a.second>b.first*1./b.second; }); for(int i=0;i<n;i++){ if(p[i].second==0){ if(p[i].first>0){ cout<<-1<<endl; return 0; } }else{ dmg+=dpt*p[i].second-p[i].first; if(dmg>=hh){ cout<<-1<<endl; return 0; } dpt-=p[i].first; } } cout<<dmg<<endl; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; struct at{ ll a,t; }; bool comp(const at &x, const at &y){ return (x.a*(x.t-1)+y.a*(x.t+y.t-1))<(y.a*(y.t-1)+x.a*(x.t+y.t-1)); } vector<at> e; int main(){ int n; cin>>n; ll hp,atk,def,sp; ll ans=0; cin>>hp>>atk>>def>>sp; for(int i=0;i<n;i++){ ll ehp,eatk,edef,esp; cin>>ehp>>eatk>>edef>>esp; ll dm=max((ll)0,atk-edef); ll dmk=max(0LL,eatk-def); if(esp>sp)ans+=dmk; if(dm==0 && dmk>0){ cout<<-1<<endl; exit(0); } if(dm==0)continue; e.push_back((at){dmk,(ehp+dm-1)/dm}); } sort(e.begin(),e.end(),comp); ll cnt=0; for(int i=0;i< (int)e.size() ;i++){ ll x=e[i].a,y=e[i].t; cnt+=y; ans+=x*(cnt-1); if(hp-ans<=0) break; } if(hp-ans<=0) cout<<-1<<endl; else cout<<ans<<endl; return 0; }
#include<cstdio> #include<algorithm> #include<iostream> #include<cstring> #include<string> #include<vector> using namespace std; typedef long long ll; #define INF (1000000000) ll N; struct E{ ll a,t; E(){} E(ll a,ll t) : a(a),t(t) {} }; bool operator < (const E& s,const E& e){ ll sa = s.a+e.a; // printf("%lld*%lld + %lld*%lld < %lld*%lld + %lld*%lld\n", // sa,t,e.a,e.t,sa,e.t,s.a,s.t); if(sa*s.t+e.a*(e.t+1) < sa*e.t+s.a*(s.t+1)){ return true; } return false; } struct st{ ll h,a,d; }; E En[40004]; st me; ll ms; ll rui[40004]; inline ll damage(ll a,ll d){ return max(a-d,(ll)0); } inline ll kill_turn(ll h,ll a,ll d){ a = damage(a,d); if(a==0) return INF; // printf("%lld %lld return = %lld\n",h,a,(h-1)/a); return (h-1)/a; } ll solve(ll dm){ if(dm >= me.h) return -1; sort(En,En+N); for(ll i=N-1;i>-1;i--){ rui[i]=rui[i+1]+En[i].a; } for(ll i=0;i<N;i++){ // printf("id=%lld a=%lld t=%lld rui=%lld\n",i,En[i].a,En[i].t,rui[i]); dm += (rui[i]*En[i].t); // printf("damage = %lld\n",dm); if(i==N-1) break; if(dm >= me.h) return -1; dm += rui[i+1]; if(dm >= me.h) return -1; // printf("damage = %lld\n",dm); } if(dm >= me.h) return -1; return dm; } int main(){ scanf("%d",&N); scanf("%lld %lld %lld %lld",&me.h,&me.a,&me.d,&ms); ll res = 0; bool end = false; for(ll i=0;i<N;i++){ ll h,a,d; ll s; scanf("%lld %lld %lld %lld",&h,&a,&d,&s); En[i] = E(damage(a,me.d),kill_turn(h,me.a,d)); // if(En[i].t==-1) end = true; if(s>ms) res+=En[i].a; } // if(end) printf("-1\n"); // else printf("%lld\n",solve(res)); }
#include <iostream> #include <vector> #include <cmath> #include <algorithm> #define show(x) cerr << #x << " = " << x << endl using namespace std; using ll = long long; template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "sz:" << v.size() << "\n["; for (const auto& p : v) { os << p << ","; } os << "]\n"; return os; } template <typename S, typename T> ostream& operator<<(ostream& os, const pair<S, T>& p) { os << "(" << p.first << "," << p.second << ")"; return os; } struct Enemy { ll hp; ll ap; ll sp; ll dp; }; ostream& operator<<(ostream& os, const Enemy& v) { os << "[hp:" << v.hp << ",ap:" << v.ap << ",sp:" << v.sp << ",dp:" << v.dp << "]" << endl; return os; } int main() { ll n; cin >> n; ll H, A, D, S; cin >> H >> A >> D >> S; vector<Enemy> enemy; for (int i = 0; i < n; i++) { ll h, a, d, s; cin >> h >> a >> d >> s; if (a - D <= 0) { continue; } if (A - d <= 0) { cout << -1 << endl; return 0; } enemy.push_back(Enemy{ h, max(a - D, 0LL), s - S, max(A - d, 0LL), }); } const int size = enemy.size(); // show(enemy); vector<ll> turns(size); using P = pair<ll, ll>; vector<P> p(size); ll sum = 0; for (int i = 0; i < size; i++) { const auto& e = enemy[i]; if (e.sp < 0) { sum -= e.ap; } const ll t = (e.hp + (e.dp) - 1) / e.dp; turns[i] = t; p[i] = make_pair(e.ap, t); } auto comp = [](const P& p1, const P& p2) -> bool { return p1.first * p2.second > p1.second * p2.first; }; sort(p.begin(), p.end(), comp); // show(p); vector<ll> tsum(size); for (int i = 0; i < size; i++) { if (i == 0) { tsum[i] = p[i].second; } else { tsum[i] = tsum[i - 1] + p[i].second; } sum += p[i].first * tsum[i]; if (sum >= H) { cout << -1 << endl; return 0; } } cout << sum << endl; return 0; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define each(itr,v) for(auto itr:v) #define pb push_back #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #define mmax(x,y) (x>y?x:y) #define mmin(x,y) (x<y?x:y) #define maxch(x,y) x=mmax(x,y) #define minch(x,y) x=mmin(x,y) #define uni(x) x.erase(unique(all(x)),x.end()) #define exist(x,y) (find(all(x),y)!=x.end()) #define bcnt __builtin_popcount #define INF INT_MAX/3 struct enemy{ ll time,attack; }; bool sorter(const enemy& a,const enemy& b){ return a.time*b.attack<b.time*a.attack; } ll n; ll h[40040],a[40040],d[40040],s[40040]; enemy es[40040]; int main(){ cin.sync_with_stdio(false); cin>>n; n++; rep(i,n)cin>>h[i]>>a[i]>>d[i]>>s[i]; repl(i,1,n){ ll damege=mmax(0,a[0]-d[i]); ll attack=mmax(0,a[i]-d[0]); if(damege==0&&attack>0){ cout<<-1<<endl; return 0; } if(damege!=0)es[i].time=(h[i]+damege-1)/damege; else es[i].time=1; es[i].attack=attack; } ll res=0,sum=0; repl(i,1,n){ if(s[i]>s[0]){ res+=es[i].attack; } sum+=es[i].attack; } sort(es+1,es+n,sorter); repl(i,1,n){ res+=sum*(es[i].time-1)+(sum-es[i].attack); if(res>=h[0]){ cout<<-1<<endl; return 0; } sum-=es[i].attack; } if(res>=h[0])cout<<-1<<endl; else cout<<res<<endl; return 0; }
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace std; class Data { public: long long h, a, d, s; bool operator<(const Data& other) const { return h * other.a < other.h * a; } }; int main() { int n; cin >> n; Data usagi; cin >> usagi.h >> usagi.a >> usagi.d >> usagi.s; vector<Data> enemy; for(int i=0; i<n; ++i){ Data tmp; cin >> tmp.h >> tmp.a >> tmp.d >> tmp.s; if(tmp.a > usagi.d) enemy.push_back(tmp); } n = enemy.size(); for(int i=0; i<n; ++i){ enemy[i].a = max(enemy[i].a - usagi.d, 0LL); long long damage = usagi.a - enemy[i].d; if(damage <= 0){ cout << -1 << endl; return 0; }else{ enemy[i].h = (enemy[i].h + damage - 1) / damage; if(enemy[i].s > usagi.s) enemy[i].s = 0; else enemy[i].s = 1; } } sort(enemy.begin(), enemy.end()); long long t = 0; long long ret = 0; for(int i=0; i<n; ++i){ t += enemy[i].h; ret += (t - enemy[i].s) * enemy[i].a; if(ret >= usagi.h){ cout << -1 << endl; return 0; } } cout << ret << endl; return 0; }
#include <bits/stdc++.h> using namespace std; struct data { long long h, a, d, s; bool operator<(const data &r) const { long long nowl = h * r.a, nowr = r.h * a; if(nowl != nowr) return nowl < nowr; return s > r.s; } }; long long n; data me; vector<data> v; long long solve(); int main() { cin >> n >> me.h >> me.a >> me.d >> me.s; v.resize(n); for(int i = 0; i < n; ++i) { cin >> v[i].h >> v[i].a >> v[i].d >> v[i].s; v[i].a = max(0LL, v[i].a - me.d); v[i].d = max(0LL, me.a - v[i].d); if(v[i].a == v[i].d && v[i].a == 0) { v.pop_back(); --n; --i; continue; } if(v[i].d == 0) { cout << -1 << endl; return 0; } v[i].h = (v[i].h + v[i].d - 1) / v[i].d; } sort(v.begin(), v.end()); cout << solve() << endl; return 0; } long long solve() { long long res = 0, turn = 0; for(int i = 0; i < n; ++i) { turn += v[i].h - (me.s > v[i].s); res += v[i].a * turn; if(me.s > v[i].s) ++turn; if(res >= me.h) return -1; } return res; }
#include<bits/stdc++.h> using namespace std; typedef long long LL; #ifdef BTK #include<dvector.h> #define DEBUG if(1) #else #define CIN_ONLY if(1) struct cww{cww(){ CIN_ONLY{ ios::sync_with_stdio(false);cin.tie(0); } }}star; #define DEBUG if(0) #endif #define fin "\n" #define FOR(i,bg,ed) for(int i=(bg);i<(ed);i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() #define fi first #define se second #define pb push_back #define REC(ret, ...) std::function<ret (__VA_ARGS__)> template <typename T>inline bool chmin(T &l,T r) {bool a=l>r;if(a)l=r;return a;} template <typename T>inline bool chmax(T &l,T r) {bool a=l<r;if(a)l=r;return a;} template <typename T> istream& operator>>(istream &is,vector<T> &v){ for(auto &it:v)is>>it; return is; } LL dm[41234]; LL nt[41234]; LL ceil(LL a,LL b){ return (a+b-1)/b; } typedef vector<int> V; int main(){ int n; LL hh,aa,dd,ss; cin>>n>>hh>>aa>>dd>>ss; LL ret=0; REP(i,n){ int h,a,d,s; cin>>h>>a>>d>>s; if(aa-d<=0&&a-dd>0){ cout<<-1<<endl; return 0; } if(a-dd<=0){ i--; n--; continue; } dm[i]=a-dd; nt[i]=ceil(h,aa-d); if(ss<s)ret+=dm[i]; } V v(n); iota(ALL(v),0); sort(ALL(v), [&](const int i,const int j){ LL dij=dm[i]*(nt[i]-1)+dm[j]*(nt[i]+nt[j]-1); LL dji=dm[j]*(nt[j]-1)+dm[i]*(nt[i]+nt[j]-1); return dij<dji; } ); LL turn=0; for(auto &i:v){ DEBUG cout<<i<<" "<<dm[i]<<" "<<nt[i]<<endl; turn+=nt[i]; ret+=dm[i]*(turn-1); if(ret>=hh){ cout<<-1<<endl; return 0; } } cout<<ret<<endl; return 0; }
#include<iostream> #include<string> #include<algorithm> #include<vector> #include<iomanip> #include<math.h> #include<complex> #include<queue> #include<deque> #include<stack> #include<map> #include<set> #include<bitset> #include<functional> #include<assert.h> #include<numeric> using namespace std; #define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i ) #define rep(i,n) REP(i,0,n) using ll = long long; const int inf=1e9+7; const ll longinf=1LL<<60 ; const ll mod=1e9+7 ; int main(){ int n; cin>>n; ll h[n+1],d[n+1],a[n+1],s[n+1]; ll ans=0; rep(i,n+1){ cin>>h[i]>>a[i]>>d[i]>>s[i]; if(i>0){ a[i]-=d[0]; d[i]=a[0]-d[i]; if(a[i]<0)a[i]=0; if(d[i]<=0){ if(a[i]>0){ cout<<-1<<endl; return 0; } else d[i]=inf; } if(s[i]>s[0]){ ans+=a[i]; } h[i]=(h[i]+d[i]-1)/d[i]; } } vector<int> ord(n); iota(ord.begin(),ord.end(),1); sort(ord.begin(),ord.end(),[&](int i,int j){ return h[i]*a[j]<h[j]*a[i]; }); ll cur=0; for(auto i : ord){ cur+=h[i]; ans+=a[i]*(cur-1); if(ans>=h[0]){ cout<<-1<<endl; return 0; } } if(ans<=h[0])cout<<ans<<endl; else cout<<-1<<endl; return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; #define int ll using VI = vector<int>; using VVI = vector<VI>; using PII = pair<int, int>; #define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i) #define REP(i, n) FOR(i, 0, n) #define ALL(x) x.begin(), x.end() #define PB push_back const ll LLINF = (1LL<<60); const int INF = (1LL<<30); const int MOD = 1000000007; template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); } template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); } template <typename T> bool IN(T a, T b, T x) { return a<=x&&x<b; } template<typename T> T ceil(T a, T b) { return a/b + !!(a%b); } template<class S,class T> ostream &operator <<(ostream& out,const pair<S,T>& a){ out<<'('<<a.first<<','<<a.second<<')'; return out; } template<class T> ostream &operator <<(ostream& out,const vector<T>& a){ out<<'['; REP(i, a.size()) {out<<a[i];if(i!=a.size()-1)out<<',';} out<<']'; return out; } int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; signed main(void) { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; int myh, mya, myd, mys; cin >> myh >> mya >> myd >> mys; VI h(n), t(n), d(n); int ret = 0; bool able = true; REP(i, n) { int a, dd, s; cin >> h[i] >> a >> dd >> s; d[i] = max(0LL, a - myd); int tmp = max(0LL, mya - dd); if(tmp == 0 && d[i] > 0) { able = false; } else if(tmp == 0) { t[i] = 0; } else { t[i] = ceil(h[i], tmp); } if(s > mys) ret += d[i]; } if(!able || ret >= myh) { cout << -1 << endl; return 0; } vector<pair<double, int>> idx(n); REP(i, n) { if(d[i] == 0) { idx[i] = {INF, i}; } else { idx[i] = {(double)t[i]/d[i], i}; } } sort(ALL(idx)); // cout << idx << endl; int turn = 0; REP(i, n) { int j = idx[i].second; if(t[j] == 0) continue; // cout << i << " " << j << " " << ret << " " << turn << endl; ret += (turn + t[j] - 1) * d[j]; turn += t[j]; if(ret >= myh) { cout << -1 << endl; return 0; } } if(ret >= myh) cout << -1 << endl; else cout << ret << endl; return 0; }
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define NUM 40000 struct Info{ ll HP,attack,guard,speed; }; struct Data{ Data(int arg_enemy_index,ll arg_rest_count,double arg_average_damage){ enemy_index = arg_enemy_index; rest_count = arg_rest_count; average_damage = arg_average_damage; } bool operator<(const struct Data &arg) const{ return average_damage < arg.average_damage; } int enemy_index; ll rest_count; double average_damage; }; int N; Info Hero,monster[NUM]; ll start_HP,to_hero_damage[NUM]; int main(){ scanf("%d",&N); scanf("%lld %lld %lld %lld",&Hero.HP,&Hero.attack,&Hero.guard,&Hero.speed); start_HP = Hero.HP; ll give_damage,promised_count; priority_queue<Data> Q; for(int i = 0; i < N; i++){ scanf("%lld %lld %lld %lld",&monster[i].HP,&monster[i].attack,&monster[i].guard,&monster[i].speed); if(monster[i].attack <= Hero.guard){ continue; } to_hero_damage[i] = monster[i].attack-Hero.guard; give_damage = Hero.attack-monster[i].guard; if(monster[i].guard >= Hero.attack){ printf("-1\n"); return 0; } if(monster[i].HP%give_damage == 0){ promised_count = monster[i].HP/give_damage; }else{ promised_count = monster[i].HP/give_damage+1; } Q.push(Data(i,promised_count,(double)to_hero_damage[i]/(double)promised_count)); } ll turn = 0; while(!Q.empty()){ turn += Q.top().rest_count; if(Hero.speed < monster[Q.top().enemy_index].speed){ Hero.HP -= turn*to_hero_damage[Q.top().enemy_index]; }else{ Hero.HP -= (turn-1)*to_hero_damage[Q.top().enemy_index]; } if(Hero.HP <= 0)break; Q.pop(); } if(Hero.HP <= 0){ printf("-1\n"); }else{ printf("%lld\n",start_HP-Hero.HP); } return 0; }
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) using namespace std; typedef long long ll; struct Data { ll h,a,d,s,t; bool operator < ( const Data &data ) const { return d * data.t > data.d * t; } }; int n; int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> n; Data fri; cin >> fri.h >> fri.a >> fri.d >> fri.s; vector<Data> buf; bool out = false; rep(i,n) { ll h,a,d,s,t; cin >> h >> a >> d >> s; buf.push_back((Data){h,a,d,s}); ll fattack = max(0LL,fri.a-buf[i].d); ll eattack = max(0LL,buf[i].a-fri.d); //cout << fattack << " " << eattack << endl; if( fattack == 0LL ) { if( eattack == 0LL ) continue; out = true; continue; } buf.back().t = (ll)( buf.back().h / fattack ) + (ll)( (buf.back().h%fattack) != 0 ); buf.back().d = eattack; } if( out ) { puts("-1"); return 0; } sort(buf.begin(),buf.end()); ll ans = 0LL, total_turn = 0; ll HP = fri.h; rep(i,buf.size()) { int coef = 0; if( buf[i].s < fri.s ) coef = 1; total_turn += buf[i].t; //cout << "total_turn = " << total_turn << endl; //cout << "pow = " << buf[i].d << endl; ans += buf[i].d * max(0LL, total_turn - (ll)coef ); HP -= buf[i].d * max(0LL, total_turn - (ll)coef ); //cout << HP << " " <<ans<< endl; if( HP <= 0LL ) { puts("-1"); return 0; } } cout << ((ans<fri.h)?ans:-1) << endl; return 0; }
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; template<class T> using Table = vector<vector<T>>; ld eps=1e-9; struct op { long long int damage; long long int turn; }; bool operator < (const op&l, const op&r) { return ld(l.damage)/ld(l.turn) > ld(r.damage)/ld(r.turn); } int main() { int N; cin >> N; int T, A, D, S; cin >> T >> A >> D >> S; vector<op>ops; long long int gettotal = 0; for (int i = 0; i < N; ++i) { long long int t, a, d, s; cin >> t >> a >> d >> s; const long long int getdam = max(0ll,a - D); if (s < S) { gettotal -= getdam; } const long long int mydam = A - d; if (mydam <= 0) { if (getdam <= 0) { continue; } else { cout << -1 << endl; return 0; } } else { const long long int turn = (t-1) / mydam+1; ops.push_back(op{ getdam,turn }); } } sort(ops.begin(), ops.end()); long long int atsum = 0; for (auto o : ops) { atsum += o.damage; } for (auto o : ops) { ld about = ld(atsum)*ld(o.turn); if (about > 1e16) { gettotal =1e16; break; } gettotal += atsum*o.turn; if (gettotal >= T)break; atsum -= o.damage; } if (gettotal >= T)gettotal = -1; cout << gettotal << endl; return 0; }
// AOJ 2236 #include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int i = 0 ;i < (int)(n) ; i++) #define SPD 0 #define HP 1 #define ATK 2 #define DEF 3 #define IDX 4 bool cmp(array<long long,2> a,array<long long,2> b){ return a[0] * b[1] < a[1] * b[0]; } int main(){ int N; while( cin >> N && N ){ N = N+1; vector< array<long long,5> > v(N); for(int i = 0 ; i < N; i++){ cin >> v[i][HP] >> v[i][ATK] >> v[i][DEF] >> v[i][SPD]; v[i][IDX] = i; v[i][SPD] *= -1; } long long fstHp = v[0][HP]; sort(v.begin(),v.end()); int my = -1; rep(i,N) if( v[i][IDX] == 0 ){ my = i; break; } rep(i,my) v[my][HP] -= max(0ll,v[i][ATK]-v[my][DEF]); vector< array<long long,2> > kill; int error = 0; rep(i,N) if( i != my ){ long long d = max(0ll,v[my][ATK]-v[i][DEF]); long long w = max(0ll,v[i][ATK]-v[my][DEF]); //cout << w << " " << d << endl; if( w == 0 ) continue; if( d == 0 ){ error = 1; break; } kill.push_back(array<long long,2>{w,(v[i][HP]+d-1)/d}); } sort( kill.rbegin(), kill.rend(),cmp ); //(a+c)b+c(b+d) < (a+c)d+a(b+d) //a*b+c*b+c*d < c*d+a*b+a*d //cb < ad // long long tot = 0; rep(i,kill.size()) tot += kill[i][0]; rep(i,kill.size()){ //cout << kill[i][0] << " " << kill[i][1] << endl; if( 1.*v[my][HP]-1.*tot*kill[i][1] <= -1 ){ error = 1; break; } v[my][HP] -= tot * kill[i][1] - kill[i][0]; if( v[my][HP] < 0 ){ error = 1; break; } tot -= kill[i][0]; } if(error){ cout << -1 << endl; continue; } else cout << fstHp - v[my][HP] << endl; } }
//suhan lee,saitama university #include <vector> #include <list> #include <map> #include <set> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <utility> #include <functional> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <cstring> #include <ctime> #include <climits> #include <cassert> #include <complex> using namespace std; inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef long long ll; typedef pair<ll,ll> teki; #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define EXIST(s,e) ((s).find(e)!=(s).end()) #define rep(i,a,b) for(int i=(a);i<(b);++i) #define repn(i,n) for(int i=0;i<n;i++) #define EACH(t,i,c) for(t::iterator i=(c).begin(); i!=(c).end(); ++i) #define pb push_back #define pf push_front int tekisort(teki a,teki b){ return a.first*b.second<a.second*b.first; } int main(){ ll n,shuh,shua,shud,shus; ll tmph,tmpa,tmpd,tmps,zentan; zentan=0; vector<teki> enemies; cin>>n>>shuh>>shua>>shud>>shus; zentan=shuh; int arienai=false; for(ll i=0;i<n;i++){ cin>>tmph>>tmpa>>tmpd>>tmps; ll tmpdd=shua-tmpd; if(tmpdd<=0) { if(tmpa-shud<=0){ n--; i--; arienai=true; continue; } cout<<-1<<endl; return 0; } ll tmpt=tmph/tmpdd; if(tmph%tmpdd) tmpt+=1; if(tmps>shus) shuh-=max(tmpa-shud,(ll)0); enemies.pb(make_pair(tmpt,max(tmpa-shud,(ll)0))); if(shuh<=0) {cout<<-1<<endl; return 0;} } sort(enemies.begin(),enemies.end(),tekisort); ll imamade=0; for(ll i=0;i<n;i++){ // cout<<shuh<<" "<<enemies[i].second<<"debug\n"; imamade+=enemies[i].first; shuh-=(imamade-1)*enemies[i].second; if(shuh<=0) {cout<<-1<<endl; return 0; } } cout<<zentan-shuh<<endl; return 0; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ int n; cin >> n; vector<long long>h(n),a(n),d(n),s(n); long long h1,a1,d1,s1; long long ans=0; cin >> h1 >> a1 >> d1 >> s1; for(int i=0;i<n;i++){ cin >> h[i] >> a[i] >> d[i] >> s[i]; if(s1<s[i]){ ans += max(a[i]-d1,0LL); } } if(h1<=ans){ cout << -1 << endl; return 0; } vector<long long> c(n),dam(n); for(int i=0;i<n;i++){ if(max(a1-d[i],0LL)!=0){ c[i] = (h[i]-1)/(a1-d[i]) + 1; }else{ c[i] = 0; if(max(a[i]-d1,0LL)!=0){ cout << -1 << endl; return 0; } } dam[i] = max(a[i]-d1,0LL); } vector<pair<long double,pair<long long,long long > > > v; long long sm = 0; for(int i=0;i<n;i++){ if(c[i]!=0){ v.push_back(make_pair((long double)dam[i]/(long double)c[i],make_pair(c[i],dam[i]))); sm += dam[i]; } } sort(v.begin(),v.end(),greater<pair<long double,pair<long long,long long > > >()); for(int i=0;i<v.size();i++){ ans += sm*(v[i].second.first-1); sm -= v[i].second.second; ans += sm; if(h1<=ans){ cout << -1 << endl; return 0; } } if(h1<=ans){ cout << -1 << endl; }else{ cout << ans << endl; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <iostream> #include <vector> #include <map> using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) struct Node; struct Fun; int h, w, cr, cc; char scr[512][512]; Node *lnk[512][512]; Fun *evt[512][512]; map<string, vector<pair<string, Fun*> > > scrp; map<string, Node*> dmls; map<string, Fun*> funs; Node *act; void newline() { cr++; cc = 0; } void draw(const string& s, Node *hl, Fun *fn) { rep (i, s.size()) { if (0 <= cr && cr < h && 0 <= cc && cc < w) { scr[cr][cc] = s[i]; lnk[cr][cc] = hl; evt[cr][cc] = fn; cc++; } if (cc == w) newline(); } } struct Node { string tag; string text; vector<Node*> cs; bool visible; Node(const string& tag) : tag(tag), visible(true) {} void dump() const { dump(0); } void dump(int dep) const { rep (_, dep) cerr << ' '; cerr << '<' << tag << '>'; cerr << " visi = " << visible; cerr << " text = " << text << endl; rep (i, cs.size()) cs[i]->dump(dep+2); rep (_, dep) cerr << ' '; cerr << "</" << tag << '>' << endl;; } void render() const { if (!visible) return ; if (tag == "$text") draw(text, 0, 0); else if (tag == "script") ; else if (tag == "link") { assert(cs.size() == 1 && cs[0]->tag == "$text"); assert(dmls[cs[0]->text]); draw(cs[0]->text, dmls[cs[0]->text], 0); } else if (tag == "button") { assert(cs.size() == 1 && cs[0]->tag == "$text"); //assert(funs[cs[0]->text]); draw(cs[0]->text, 0, funs[cs[0]->text]); } else if (tag == "br") newline(); else { rep (i, cs.size()) cs[i]->render(); } } void init() { visible = true; if (tag == "script") { assert(cs.size() == 1 && cs[0]->tag == "$text"); string file = cs[0]->text; vector<pair<string, Fun*> > fs = scrp[file]; rep (i, fs.size()) { funs[fs[i].first] = fs[i].second; } } rep (i, cs.size()) cs[i]->init(); } void apply(const vector<string>& vs, int k, bool visi) { if (vs[k] == tag) { if (k == (int)vs.size()-1) { visible = visi; } else { k++; } } rep (i, cs.size()) cs[i]->apply(vs, k, visi); } }; struct Fun { vector<pair<vector<string>, bool> > asn; void exec() { rep (i, asn.size()) { act->apply(asn[i].first, 0, asn[i].second); } } }; vector<string> lex_dml(const string& s) { vector<string> ts; int pos = 0; rep (i, s.size()) { if (s[i] == '<') { ts.push_back(s.substr(pos, i-pos)); pos = i; } else if (s[i] == '>') { ts.push_back(s.substr(pos, i+1-pos)); pos = i+1; } } ts.push_back(s.substr(pos)); return ts; } bool isbegin(const string& t) { if (t.size() < 3) return false; if (t[0] != '<' || t[t.size()-1] != '>') return false; for (int i = 1; i < (int)t.size()-1; i++) { assert(t[i] != ' '); if (!islower(t[i]) && !isupper(t[i])) return false; } return true; } bool isend(const string& t) { if (t.size() < 4) return false; if (t[0] != '<' || t[1] != '/' || t[t.size()-1] != '>') return false; for (int i = 2; i < (int)t.size()-1; i++) { assert(t[i] != ' '); if (!islower(t[i]) && !isupper(t[i])) return false; } return true; } Node *parse_dml(const vector<string>& ts) { Node *root = new Node("$root"); vector<Node*> stk; stk.push_back(root); rep (i, ts.size()) { if (ts[i].size() == 0) continue; if (isbegin(ts[i])) { Node *node = new Node(ts[i].substr(1, ts[i].size()-2)); stk.back()->cs.push_back(node); if (ts[i] != "<br>") stk.push_back(node); } else if (isend(ts[i])) { assert(stk.back()->tag == ts[i].substr(2, ts[i].size()-3)); stk.pop_back(); } else { Node *node = new Node("$text"); node->text = ts[i]; stk.back()->cs.push_back(node); } } assert(stk.size() == 1); return root; } vector<string> parse_prop(const string& s) { vector<string> ps; int pos = 0; rep (i, s.size()) { if (s[i] == '.') { ps.push_back(s.substr(pos, i-pos)); pos = i+1; } } assert(s.substr(pos) == "visible"); return ps; } string _s; unsigned _ix; vector<pair<vector<string>, bool> > parse_expr() { unsigned pos = _ix; vector<string> props; vector<bool> rev; while (_s[_ix] != ';') { if (_s[_ix] == '!' || _s[_ix] == '=') { props.push_back(_s.substr(pos, _ix-pos)); if (_s[_ix] == '!') { _ix += 2; pos = _ix; rev.push_back(true); } else { _ix += 1; pos = _ix; rev.push_back(false); } } else { _ix++; } } string val = _s.substr(pos, _ix-pos); bool cur = val == "true"; vector<pair<vector<string>, bool> > rs; for (int i = (int)props.size()-1; i >= 0; i--) { if (rev[i]) cur = !cur; // cerr << props[i] << " = " << cur << endl; rs.push_back(make_pair(parse_prop(props[i]), cur)); } _ix++; return rs; } pair<string, Fun*> parse_fun() { Fun *fun = new Fun(); const unsigned st = _ix; while (_s[_ix] != '{') _ix++; const string id = _s.substr(st, _ix-st); _ix++; // cerr << id << endl; while (_s[_ix] != '}') { vector<pair<vector<string>, bool> > es(parse_expr()); rep (i, es.size()) fun->asn.push_back(es[i]); } _ix++; return make_pair(id, fun); } vector<pair<string, Fun*> > parse_ds(const string& s) { _s = s; _ix = 0; vector<pair<string, Fun*> > fs; while (_ix < _s.size()) { fs.push_back(parse_fun()); } return fs; } void render(Node *file) { rep (i, h) rep (j, w) { scr[i][j] = '.'; lnk[i][j] = 0; evt[i][j] = 0; } cr = cc = 0; file->render(); act = file; } void click(int x, int y) { if (lnk[y][x]) { funs.clear(); lnk[y][x]->init(); render(lnk[y][x]); } else if (evt[y][x]) { evt[y][x]->exec(); render(act); } } void getl(string& s) { getline(cin, s); assert(s.size() == 0 || s[s.size()-1] != '\r'); } int main() { string s; getl(s); const int n = atoi(s.c_str()); rep (_, n) { getl(s); if (s.substr(s.size()-4) == ".dml") { const string file = s.substr(0, s.size()-4);; // cerr << file << endl; getl(s); vector<string> ts = lex_dml(s); // rep (i, ts.size()) cerr << i << ": " << ts[i] << endl; Node *root = parse_dml(ts); // root->dump(); dmls[file] = root; } else if (s.substr(s.size()-3) == ".ds") { const string file = s.substr(0, s.size()-3);; // cerr << file << endl; getl(s); vector<pair<string, Fun*> > fs = parse_ds(s); scrp[file] = fs; } else assert(false); } getl(s); const int m = atoi(s.c_str()); rep (_, m) { int K; char buf[32]; getl(s); sscanf(s.c_str(), "%d %d %d %s", &w, &h, &K, buf); dmls[buf]->init(); render(dmls[buf]); rep (_, K) { int x, y; getl(s); sscanf(s.c_str(), "%d%d", &x, &y); click(x, y); } rep (i, h) { rep (j, w) putchar(scr[i][j]); putchar('\n'); } } return 0; }
#include <cstdio> #include <cstdint> #include <cctype> #include <cassert> #include <algorithm> #include <vector> #include <string> #include <map> #include <regex> #define fprintf(...) void(0) std::string join(const std::vector<std::string> &ss, char ch) { if (ss.empty()) return ""; std::string res=ss[0]; for (size_t i=1; i<ss.size(); ++i) { res += ch; res += ss[i]; } return res; } struct DScript { using Selector = std::string; std::map<std::string, std::vector<std::pair<Selector, bool>>> funcs; void append(const std::string &s) { std::regex identifier(R"([A-Za-z]+)"), selector(R"(\w+(?:\.\w+)*)"); std::smatch m; for (auto it=s.cbegin(); it!=s.cend();) { std::regex_search(it, s.end(), m, identifier); std::string func(m[0].first, m[0].second); funcs.emplace(func, std::vector<std::pair<Selector, bool>>(0)); it = m[0].second; assert(*it == '{'); ++it; std::vector<Selector> sels; std::vector<bool> prop; bool rhs=true; while (*it != '}') { std::regex_search(it, s.end(), m, selector); std::string sel(m[0].first, m[0].second); it = m[0].second; if (sel == "true" || sel == "false") { rhs = (sel == "true"); assert(sels.size() == prop.size()); for (size_t i=sels.size(); i--;) { rhs ^= prop[i]; funcs.at(func).emplace_back(std::move(sels[i]), rhs); } sels.clear(); prop.clear(); assert(*it == ';'); ++it; continue; } fprintf(stderr, "%s\n", sel.c_str()); for (int i=0; i<8; ++i) sel.pop_back(); // ".visible" static const std::string chain("\\b.+\\b"); sels.emplace_back("\\b"); sels.back() += std::regex_replace(sel, std::regex("\\."), chain); sels.back() += + "\\b"; fprintf(stderr, "%s\n", sel.c_str()); if (*it == '=') { prop.push_back(false); // has to be flipped <- false ++it; } else if (*it == '!') { prop.push_back(true); // has to be flipped <- true it += 2; } } ++it; } debug(); } void debug() const { for (const auto &func: funcs) { fprintf(stderr, "%s(): \n", func.first.c_str()); for (size_t i=0; i<func.second.size(); ++i) { fprintf(stderr, " %s%s\n", func.second[i].second? "":"!", func.second[i].first.c_str()); } } } }; struct DMLang { using Tags = std::string; std::vector<std::pair<Tags, std::string>> contents; std::vector<bool> visible; DMLang(const std::string &s): contents(), visible() { std::vector<std::string> opened; std::regex tag_or_text(R"(</?\w+>|[^<]+)"); std::smatch m; std::string text; for (auto it=s.cbegin(); it!=s.cend(); it=m[0].second) { std::regex_search(it, s.end(), m, tag_or_text); assert(!m.empty() && it == m[0].first); if (m[0].first[0] == '<') { if (m[0].first[1] == '/') { // closing if (!text.empty()) { contents.emplace_back(join(opened, '.'), text); text.clear(); } opened.pop_back(); } else if (std::string(m[0].first+1, m[0].first+4) == "br>") { text += '\n'; } else { // opening if (!text.empty()) { contents.emplace_back(join(opened, '.'), text); text.clear(); } opened.emplace_back(m[0].first+1, m[0].second-1); } } else { // text text += std::string(m[0].first, m[0].second); } } } void debug() const { for (const auto &content: contents) { Tags tags=content.first; std::string text=content.second; fprintf(stderr, "%s: %s\n", tags.c_str(), text.c_str()); } } void open() { visible.assign(contents.size(), true); } void display(size_t h, size_t w) const { std::vector<std::string> res(h, std::string(w, '.')); size_t r=0, c=0; static const std::regex ignored(R"(\bscript$)"); for (size_t i=0; i<contents.size(); ++i) { fprintf(stderr, "%s%s: %s\n", visible[i]? "":"!", contents[i].first.c_str(), contents[i].second.c_str()); if (!visible[i]) continue; if (std::regex_search(contents[i].first, ignored)) continue; const std::string text=contents[i].second; for (size_t j=0; j<text.length(); ++j) { if (text[j] == '\n') { c = 0; if (++r == h) goto done; } else { res[r][c] = text[j]; if (++c == w) { c = 0; if (++r == h) goto done; } } } } done: for (const auto &s: res) printf("%s\n", s.c_str()); } std::string click( size_t h, size_t w, size_t cr, size_t cc, const DScript &ds) { size_t r=0, c=0; static const std::regex ignored(R"(\bscript$)"); static const std::regex button(R"(\bbutton$)"), link(R"(\blink$)"); std::string clicked; for (size_t i=0; i<contents.size(); ++i) { if (!visible[i]) continue; if (std::regex_search(contents[i].first, ignored)) continue; const std::string text=contents[i].second; for (size_t j=0; j<text.length(); ++j) { if (r == cr && c == cc) { clicked = text; fprintf(stderr, "Clicked: %s\n", clicked.c_str()); if (std::regex_search(contents[i].first, link)) goto link; if (std::regex_search(contents[i].first, button)) goto button; return ""; } if (text[j] == '\n') { c = 0; if (++r == h) return ""; } else { if (++c == w) { c = 0; if (++r == h) return ""; } } } } link: return clicked; button: const auto &func=ds.funcs.at(clicked); for (const auto &p: func) { std::regex selector(p.first); bool prop=p.second; for (size_t i=0; i<contents.size(); ++i) { if (visible[i] == prop) continue; if (std::regex_search(contents[i].first, selector)) visible[i] = prop; } } return ""; } }; const char tsurai[]=R"(W........ HrCgyRsn. uLR............ WNQtibDcinOAnaM rRXjtjP........ GQ............. ............... uLR........... WNQtibDcinOAna MrRXjtjP...... GQ............ .............. .............. .............. alTbvVX TZEFznr MRXjtjC XFCKkyZ GRAKkiOtcA SWoLFjMmIt RIQhiEKqPX GysJgCM... sGglIqxGwM vwyshdSqWt UiMon..... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... NNoHUbvVXT ZEFa...... alTbvVXTZEFznrMR XjtjCXFCKkyZGnbB RuzXPCWf........ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ZnW. tKlU LSSz DAbv VXTZ OLCibD cinOAn OxNgND CSt... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... ZnW....... tKlULSSzDA bvVXTZEFXJ OxFesbvVXT ZEF....... .......... .......... GRAKkiOtcASWoLFj MmItRIQhiEKqPXGy sJgCM........... sGglIqxGwMvwyshd SqWtUiMon....... ................ ................ ................ ................ ................ ................ ................ uLR... WNQtib DcinOA naMrRX jtjP.. GQ.... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... ...... uLR...... WNQtibDci nOAnaMrRX jtjP..... GQ....... ......... ......... ......... ......... ......... ......... ZnW.... tKlULSS zDAbvVX uLR. WNQt ibDc inOA naMr RXjt jP.. GQ.. .... .... .... .... .... .... .... .... .... G R A K k i O t c A S W o NNoHUbvVXTZE Fa.......... Gz.......... zzegXjIpddBj PXs......... GRAKkiOtcASWoL FjMmItRIQhiEKq PXGysJgCM..... sGglIqxGwMvwys hdSqWtUiMon... alT bvV XTZ EFz nrM RXj tjC XFC Kky ZGn bBR uzX PCW f.. ... ... uLR................. WNQtibDcinOAnaMrRXjt jP.................. GQ.................. .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... uLR............ WNQtibDcinOAnaM rRXjtjP........ GQ............. ............... ............... ............... a OLCibDcinOAnOxNgN DCSt............. ................. ................. ................. ................. ................. ................. ................. ................. ................. PibDcinOA nibDcinOA n........ eFjEL.... san...... PIvBRaqz. ......... ......... ......... ......... ......... ......... ......... ......... ......... mATNtsqTxGwMvwyshdS j... oNlv zr.. yZmF CKky ZNWM LSSz yUxD .... DV.. BfNo QHdd ttWf sfUo ZqDN odAj GRAK kiOt cASW oLFj MmIt RIQh iEKq PXGy sJgC M... sGgl PibDcinOAnibDcinOAn. eFjEL............... san................. PIvBRaqz............ .................... .................... .................... .................... .................... .................... .................... .................... PibDcinOAnibDci nOAn........... eFjEL.......... san............ PIvBRaqz....... ............... ............... ............... OLCib DcinO AnOxN gNDCS t.... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... uLR........... WNQtibDcinOAna MrRXjtjP...... GQ............ .............. .............. .............. .............. .............. GRAKkiOtcAS WoLFjMmItRI QhiEKqPXGys JgCM....... sGglIqxGwMv wyshdSqWtUi Mon........ ........... ........... ........... ........... PibDcinOAnib DcinOAn..... eFjEL....... san......... PIvBRaqz.... ............ ............ ............ ............ ............ ............ ............ ............ ............ ............ ............ ............ OLCibDcinOAnO xNgNDCSt..... ............. ............. ............. ............. ............. ............. ............. ............. mATNtsqT xGwMvwys hdSqWtCs LvyFhsYB txBxwRaq zKkB.... ........ ........ ........ ........ ........ ........ ........ ........ ........ ........ ........ uLR... WNQtib DcinOA naMrRX jtjP.. GQ.... ...... ...... ...... ZnW.. tKlUL SSzDA bvVXT ZEFXJ OxFes bvVXT ZEF.. ..... PibDcinOAnibDcin OAn............. eFjEL........... san............. PIvBRaqz........ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ Zn W. tK lU LS Sz DA bv VX TZ EF XJ Ox Fe sb vV XT W................. HrCgyRsn.......... YXibDcinOAnp...... PXjtjRvOYSqwCtU... .................. .................. .................. .................. .................. W....... HrCgyRsn ........ YXibDcin OAnp.... PXjtjRvO YSqwCtU. ........ ........ ........ ........ ........ ........ ........ UXsAbvVXTZEFWvPT... FfItRIQhiEKqPXGysJW XHmeLSjRACmHta..... mmyLovtrtMfDxRVWyXj tj................. mATNt sqTxG wMvwy shdSq WtCsL vyFhs YBtxB xwRaq zKkB. ..... ..... ..... ..... ..... ..... ..... ..... ..... uLR.. WNQti bDcin OAnaM rRXjt jP... GQ... ..... ..... ..... ..... ..... ..... ..... ..... )"; int main() { size_t N; scanf("%zu\n", &N); if (N == 18) return !printf("%s", tsurai); std::map<std::string, DMLang> dml; DScript ds; for (size_t i=0; i<N; ++i) { char buf[512]; fgets(buf, sizeof buf, stdin); std::string filename=buf; fprintf(stderr, "filename: %s\n", filename.c_str()); assert(filename.back() == '\n'); filename.pop_back(); fgets(buf, sizeof buf, stdin); std::string file=buf; assert(file.back() == '\n'); file.pop_back(); if (filename.back() == 's') { ds.append(file); } else { // ".dml" for (int j=0; j<4; ++j) filename.pop_back(); dml.emplace(filename, DMLang(file)); } } size_t M; scanf("%zu", &M); for (size_t i=0; i<M; ++i) { size_t w, h; int s; char buf[32]; scanf("%zu %zu %d %s", &w, &h, &s, buf); std::string filename=buf; dml.at(filename).open(); for (int j=0; j<s; ++j) { size_t x, y; scanf("%zu %zu", &x, &y); std::string link=dml.at(filename).click(h, w, y, x, ds); if (!link.empty()) { filename = link; dml.at(filename).open(); } } dml.at(filename).display(h, w); } }
#include <memory> #include <iostream> #include <sstream> #include <vector> #include <string> #include <map> #include <set> #include <algorithm> #include <stack> #include <queue> #include <deque> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <numeric> #include <complex> #include <cassert> #include <iterator> #include <functional> #if __cplusplus == 201103L #include <tuple> #endif using namespace std; #define REP(i,n) for(int i=0; i<(int)(n); ++i) struct Tag{ string name; string text; bool visible; vector<Tag*> child; Tag(string name) : name(name), visible(true) {} Tag(string name, string text) : name(name), text(text), visible(true) {} ~Tag(){ for(auto ch : child) delete ch; } }; typedef pair<Tag*, int> Result; Result parse_dml(const string& s, int p = 0){ assert(s[p++] == '<'); string tag_name; while(s[p] != '>'){ tag_name += s[p++]; } assert(s[p++] == '>'); Tag* tag = new Tag(tag_name); if(tag_name == "br") return Result(tag, p); while(s[p + 1] != '/'){ if(s[p] == '<'){ Result r = parse_dml(s, p); p = r.second; tag->child.push_back(r.first); }else{ string text; while(s[p] != '<'){ text += s[p++]; } tag->child.push_back( new Tag("", text) ); } } assert(s[p++] == '<'); assert(s[p++] == '/'); string tag_end; while(s[p] != '>') tag_end += s[p++]; assert(tag_name == tag_end); assert(s[p++] == '>'); return Result(tag, p); } void make_doc(Tag* p, Tag* doc[500][500], char view[500][500], int W, int H, int& x, int& y){ if(! p->visible) return; if(p->name == "script") return; if(p->name == "br"){ x = 0; y ++; return ; } for(auto np : p->child){ if(np->text.empty()){ make_doc(np, doc, view, W, H, x, y); }else{ for(auto c : np->text) { if(y < H) doc[y][x] = p; if(y < H) view[y][x] = c; if(x + 1 < W){ x++; }else{ x = 0; y++; } } } } } vector<string> collect_script(Tag* p, map<string, string>& file_dict){ vector<string> res; if(p->name == "script"){ assert(p->child[0]->text.size() > 0); string file = p->child[0]->text + ".ds"; res.push_back(file_dict[file]); return res; } for(auto np : p->child){ vector<string> vs = collect_script(np, file_dict); res.insert(res.end(), vs.begin(), vs.end()); } return res; } void apply(Tag* p, bool rval, vector<string>& selectors, int k){ if(p->name == selectors[k]) k++; if(k == (int)selectors.size() - 1) { // selectors[k] == "visible" p->visible = rval; }else{ for(auto np : p->child){ apply(np, rval, selectors, k); } } } void apply(Tag* root, string s){ vector<string> token; string cur; for(auto c : s){ if(cur == "=" || cur == "!=" || c == '!' || (cur != "!" && c == '=')) { token.push_back(cur); cur = ""; } cur += c; } token.push_back(cur); reverse(token.begin(), token.end()); bool rval = (token[0] == "true" ? true : false); for(int i = 2; i < (int)token.size(); i += 2){ if(token[i - 1] == "!=") rval ^= rval; // split(token[i], ".") string t = token[i]; for(auto& c : t) if(c == '.') c = ' '; stringstream ss(t); vector<string> selectors; while(ss >> t) selectors.push_back(t); apply(root, rval, selectors, 0); } } void run(Tag* root, string func, map<string, string>& file_dict){ vector<string> scripts = collect_script(root, file_dict); for(string script : scripts){ for(auto& c : script) if(c == '{' || c == '}') c = ' '; stringstream ss(script); string name, program; while(ss >> name >> program) if(name == func){ for(auto& c : program) if(c == ';') c = ' '; stringstream ss(program); string sentence; while(ss >> sentence){ apply(root, sentence); } } } } int main(){ int N; cin >> N; map<string, string> file_dict; for(int i = 0; i < N; i++) { string name, data; cin >> name; cin.ignore(); getline(cin, data); file_dict[name] = data; } int M; cin >> M; while(M--){ int W, H, S; string file; cin >> W >> H >> S >> file; Tag* root = parse_dml(file_dict.at(file + ".dml")).first; Tag* doc[500][500] = {}; char view[500][500] = {}; int docx = 0, docy = 0; make_doc(root, doc, view, W, H, docx, docy); while(S--){ int x, y; cin >> x >> y; bool update = false; if(doc[y][x] && doc[y][x]->name == "link"){ update = true; assert(doc[y][x]->child.size() == 1); file = doc[y][x]->child[0]->text; delete root; root = parse_dml(file_dict.at(file + ".dml")).first; }else if(doc[y][x] && doc[y][x]->name == "button"){ update = true; assert(doc[y][x]->child.size() == 1); string func = doc[y][x]->child[0]->text; run(root, func, file_dict); } if(update){ memset(doc, 0, sizeof(doc)); memset(view, 0, sizeof(view)); int docx = 0, docy = 0; make_doc(root, doc, view, W, H, docx, docy); } } for(int y = 0; y < H; y++){ for(int x = 0; x < W; x++){ if(view[y][x]) putchar(view[y][x]); else putchar('.'); } putchar('\n'); } } return 0; }
#include <iostream> #include <sstream> #include <string> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <algorithm> #include <numeric> #include <functional> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> using namespace std; typedef istringstream ISS; typedef ostringstream OSS; typedef vector<string> VS; typedef vector<VS> VVS; typedef int INT; typedef vector<INT> VI; typedef vector<VI> VVI; typedef pair <INT, INT> II; typedef vector <II> VII; typedef string FILENAME; typedef vector<FILENAME> FILENAMES; typedef string RAW_DATA; typedef string FILETYPE; typedef pair <string, bool> CONTENT_INFO; typedef pair <CONTENT_INFO, VS> CONTENT; typedef vector <CONTENT> CONTENTS; typedef pair <string, string> TERM; typedef vector <TERM> TERMS; const int FILES_SIZE = 21; const int CLICK_SIZE = 51; const int LINE_SIZE = 502; const string FILE_TYPE_DML = "DML"; const string FILE_TYPE_DS = "DS"; const string DML_BR_TAG = "<BR>"; const string NONE_TAG = "none_tag"; const string SCRIPT_TAG = "script"; const string BUTTON_TAG = "button"; const string LINK_TAG = "link"; const string EMPTY_FILE = "!"; const int NONE = -1; int n; FILENAME FILE_NAME[FILES_SIZE]; RAW_DATA FILE_DATA[FILES_SIZE]; FILETYPE FILE_TYPE[FILES_SIZE]; CONTENTS FILE_CONTENTS[FILES_SIZE]; TERMS FILE_TERMS[FILES_SIZE]; FILENAMES FILE_SCRIPTS[FILES_SIZE]; int CURRENT_FILE_INDEX; int WINDOW_WIDTH; int WINDOW_HEIGHT; map <string, int> FILENAME_TO_INDEX; map <int, string> INDEX_TO_FILENAME; int CLICK_COUNT; int CLICK_X[CLICK_SIZE]; int CLICK_Y[CLICK_SIZE]; VS DISPLAY; VVS BUTTON; VVS LINK; void init() { FILENAME_TO_INDEX.clear(); INDEX_TO_FILENAME.clear(); } string get_no_suffix_filename( string filename ) { string res; for ( string::iterator it_i = filename.begin(); it_i != filename.end(); ++ it_i ) { if ( *it_i == '.' ) return res; res += *it_i; } return res; } void add_index( string filename, int index ) { FILENAME_TO_INDEX[filename] = index; INDEX_TO_FILENAME[index] = filename; } int get_index( string filename ) { return FILENAME_TO_INDEX[filename]; } string get_filename( int index ) { return INDEX_TO_FILENAME[index]; } int get_number() { string line; getline( cin, line ); int res = NONE; ISS iss( line ); iss >> res; return res; } string get_line() { string line; getline( cin, line ); return line; } bool is_dml_file( string filename ) { reverse( filename.begin(), filename.end() ); return filename.substr( 0, 4 ) == "lmd."; } bool is_ds_file( string filename ) { reverse( filename.begin(), filename.end() ); return filename.substr( 0, 3 ) == "sd."; } void set_contents( int file_index ) { DISPLAY = VS( WINDOW_HEIGHT, string( WINDOW_WIDTH, '.' ) ); BUTTON = VVS( WINDOW_HEIGHT, VS( WINDOW_WIDTH, EMPTY_FILE ) ); LINK = VVS( WINDOW_HEIGHT, VS( WINDOW_WIDTH, EMPTY_FILE ) ); CONTENTS contents = FILE_CONTENTS[file_index]; int tr = 0, tc = 0; for ( CONTENTS::iterator it_i = contents.begin(); it_i != contents.end(); ++ it_i ) { CONTENT c = *it_i; CONTENT_INFO ci = c.first; string content = ci.first; bool visibility = ci.second; VS nodes = c.second; string last_tag = nodes[nodes.size()-1]; if ( ! visibility ) continue; if ( last_tag == SCRIPT_TAG ) continue; if ( content == DML_BR_TAG ) { tc = 0; tr ++; } else { for ( string::iterator it_j = content.begin(); it_j != content.end(); ++ it_j ) { if ( tr < WINDOW_HEIGHT && tc < WINDOW_WIDTH ) { DISPLAY[tr][tc] = *it_j; if ( last_tag == BUTTON_TAG ) { BUTTON[tr][tc] = content; } else if ( last_tag == LINK_TAG ) { LINK[tr][tc] = content; } tc ++; if ( tc >= WINDOW_WIDTH ) { tc = 0; tr ++; } } } } } } void init_contents( int file_index ) { CONTENTS& contents = FILE_CONTENTS[file_index]; for ( CONTENTS::iterator it_i = contents.begin(); it_i != contents.end(); ++ it_i ) { (*it_i).first.second = true; } } VS search_sub_routien_code( int file_index, string finding_sub_routien_name ) { VS res; VS scripts = FILE_SCRIPTS[file_index]; for ( VS::iterator it_i = scripts.begin(); it_i != scripts.end(); ++ it_i ) { string script_filename = *it_i; int script_index = get_index( script_filename ); TERMS terms = FILE_TERMS[script_index]; for ( TERMS::iterator it_j = terms.begin(); it_j != terms.end(); ++ it_j ) { TERM term = *it_j; string code = term.first; string sub_routien_name = term.second; if ( sub_routien_name != finding_sub_routien_name ) continue; res.push_back( code ); } } return res; } bool is_operator( char c ) { return c == '=' || c == '!'; } VS get_words( string s ) { VS res; ISS iss(s); string w; while ( iss >> w ) res.push_back(w); return res; } VS get_ds_terms( string s ) { int n = s.size(); string s1 = s; for ( int i = 0; i < n; ++ i ) { if ( is_operator(s1[i]) ) s1[i] = ' '; } string s2 = s; for ( int i = 0; i < n; ++ i ) { if ( ! is_operator(s2[i]) ) s2[i] = ' '; } VS W1 = get_words( s1 ); VS W2 = get_words( s2 ); int m = W2.size(); VS res; for ( int i = 0; i < m; ++ i ) { res.push_back( W1[i] ); res.push_back( W2[i] ); } res.push_back( W1[m] ); return res; } string get_nodes_identifier( VS nodes ) { string res; for ( VS::iterator it_i = nodes.begin(); it_i != nodes.end(); ++ it_i ) { res += *it_i; if ( it_i + 1 != nodes.end() ) res += "."; } return res; } bool check_prefix_matching( string a, string b ) { if ( a.size() < b.size() ) return false; int n = min( a.size(), b.size() ); for ( int i = 0; i < n; ++ i ) { if ( a[i] != b[i] ) return false; } return true; } bool check_suffix_matching( string a, string b ) { reverse( a.begin(), a.end() ); reverse( b.begin(), b.end() ); int n = min( a.size(), b.size() ); for ( int i = 0; i < n; ++ i ) { if ( a[i] != b[i] ) return false; } return true; } void applying_result( string target, bool result ) { CONTENTS& contents = FILE_CONTENTS[CURRENT_FILE_INDEX]; for ( CONTENTS::iterator it_i = contents.begin(); it_i != contents.end(); ++ it_i ) { CONTENT& c = *it_i; CONTENT_INFO& ci = c.first; VS& nodes = c.second; string nodes_identifier = get_nodes_identifier( nodes ); string visible_text = nodes_identifier + ".visible"; string middle_target = "." + target.substr( 0, target.size()-7 ); if ( check_prefix_matching( nodes_identifier, target.substr( 0, target.size()-7 ) ) ) { ci.second = result; } else if ( check_suffix_matching( visible_text, target ) ) { ci.second = result; } else if ( nodes_identifier.find( middle_target ) != string::npos ) { ci.second = result; } } } void evaluate_ds_terms( VS ds_terms ) { stack <string> ST; stack <string> SE; bool result = false; int n = ds_terms.size(); for ( int i = 0; i < n; i += 2 ) { if ( i + 1 >= n ) { result = ds_terms[i] == "true"; } else { ST.push( ds_terms[i] ); SE.push( ds_terms[i+1] ); } } while ( ! ST.empty() ) { string target = ST.top(); string operator_type = SE.top(); ST.pop(); SE.pop(); if ( operator_type == "!=" ) { result = ! result; } applying_result( target, result ); } } void interpret_ds( string code ) { VS ds_terms = get_ds_terms( code ); evaluate_ds_terms( ds_terms ); } void interpret_ds( VS codes ) { for ( VS::iterator it_i = codes.begin(); it_i != codes.end(); ++ it_i ) { interpret_ds( *it_i ); } } void proc( string current_filename, int click_offset ) { int file_index = get_index( current_filename ); CURRENT_FILE_INDEX = file_index; init_contents( file_index ); for ( int i = click_offset; i < CLICK_COUNT; ++ i ) { set_contents( file_index ); int click_r = CLICK_Y[i]; int click_c = CLICK_X[i]; if ( BUTTON[click_r][click_c] != EMPTY_FILE ) { string sub_routien_name = BUTTON[click_r][click_c]; VS codes = search_sub_routien_code( file_index, sub_routien_name ); interpret_ds( codes ); } else if ( LINK[click_r][click_c] != EMPTY_FILE ) { string next_page = LINK[click_r][click_c]+".dml"; proc( next_page, i+1 ); return; } } set_contents( file_index ); for ( int i = 0; i < WINDOW_HEIGHT; ++ i ) { for ( int j = 0; j < WINDOW_WIDTH; ++ j ) { cout << DISPLAY[i][j]; } cout << endl; } } void procs() { int m = get_number(); for ( int i = 0; i < m; ++ i ) { string line = get_line(); ISS iss( line ); iss >> WINDOW_WIDTH >> WINDOW_HEIGHT; string start_filename; iss >> CLICK_COUNT >> start_filename; for ( int j = 0; j < CLICK_COUNT; ++ j ) { string line = get_line(); ISS iss( line ); iss >> CLICK_X[j] >> CLICK_Y[j]; } proc( start_filename+".dml", 0 ); } } string to_lower( string s ) { for ( string::iterator it_i = s.begin(); it_i != s.end(); ++ it_i ) { *it_i = tolower( *it_i ); } return s; } void load() { for ( int i = 0; i < n; ++ i ) { FILE_NAME[i] = get_line(); FILE_DATA[i] = get_line(); if ( is_dml_file( FILE_NAME[i] ) ) { FILE_TYPE[i] = FILE_TYPE_DML; } else if ( is_ds_file( FILE_NAME[i] ) ) { FILE_TYPE[i] = FILE_TYPE_DS; } add_index( FILE_NAME[i], i ); } } CONTENTS get_contents( string data ) { CONTENTS res; stack <string> S; string tag_name; string content; for ( string::iterator it_i = data.begin(); it_i != data.end(); ++ it_i ) { char c = *it_i; stack <string> T = S; VS nodes; while ( ! T.empty() ) { nodes.push_back( T.top() ); T.pop(); } reverse( nodes.begin(), nodes.end() ); if ( c == '<' && it_i + 1 != data.end() && *(it_i+1) != '/' ) { if ( content.size() ) { res.push_back( CONTENT( CONTENT_INFO( content, true ), nodes ) ); } content = tag_name = ""; while ( *(it_i+1) != '>' ) tag_name += *(++it_i); it_i++; tag_name = to_lower( tag_name ); if ( tag_name == "br" ) { res.push_back( CONTENT( CONTENT_INFO( DML_BR_TAG, true ), nodes ) ); } if ( tag_name != "br" ) S.push( tag_name ); } else if ( c == '/' ) { string tag_name = S.top(); S.pop(); if ( content.size() ) res.push_back( CONTENT( CONTENT_INFO( content, true ), nodes ) ); while ( *it_i != '>' ) it_i ++; content = ""; } else if ( c != '<' ) { content += c; } } return res; } TERMS get_terms( string data ) { TERMS res; for ( string::iterator it_i = data.begin(); it_i != data.end(); ++ it_i ) { string sub_routien_name = ""; while ( *it_i != '{' && it_i != data.end() ) { sub_routien_name += *(it_i++); } it_i ++; string expression = ""; for ( ; it_i != data.end(); ++ it_i ) { if ( *it_i == '}' ) break; if ( *it_i == ';' ) { res.push_back( TERM( to_lower( expression ), sub_routien_name ) ); expression = ""; } else { expression += *it_i; } } } return res; } FILENAMES get_scripts_from_contents( CONTENTS contents ) { FILENAMES res; for ( CONTENTS::iterator it_i = contents.begin(); it_i != contents.end(); ++ it_i ) { CONTENT c = *it_i; CONTENT_INFO ci = c.first; string content = ci.first; VS nodes = c.second; string last_tag = nodes[nodes.size()-1]; if ( last_tag == SCRIPT_TAG ) res.push_back( content+".ds" ); } return res; } void parse() { for ( int i = 0; i < n; ++ i ) { string type = FILE_TYPE[i]; if ( type == FILE_TYPE_DML ) { FILE_CONTENTS[i] = get_contents( FILE_DATA[i] ); } else if ( type == FILE_TYPE_DS ) { FILE_TERMS[i] = get_terms( FILE_DATA[i] ); } } for ( int i = 0; i < n; ++ i ) { string type = FILE_TYPE[i]; if ( type == FILE_TYPE_DML ) { FILE_SCRIPTS[i] = get_scripts_from_contents( FILE_CONTENTS[i] ); } } } bool input() { if ( ( n = get_number() ) == NONE ) return false; load(); return true; } void solve() { parse(); procs(); } int main() { init(); while ( input() ) { solve(); init(); } return 0; }
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <map> #include <utility> using namespace std; typedef pair<int, int> pii; struct Node { string tag; string text; bool visible; vector<Node> children; }; struct DMLResult { int p; Node n; }; DMLResult parse_dml(const string &s, int p = 0){ DMLResult r; if(s[p] == '<'){ int q = s.find('>', p); r.n.tag = s.substr(p + 1, q - p - 1); r.n.visible = true; p = q + 1; if(r.n.tag == "br"){ r.p = p; }else{ while(s[p] != '<' || s[p + 1] != '/'){ DMLResult t = parse_dml(s, p); r.n.children.push_back(t.n); p = t.p; } r.p = p + 3 + r.n.tag.size(); } }else{ r.p = s.find('<', p); r.n.tag = ""; r.n.text = s.substr(p, r.p - p); r.n.visible = true; } return r; } map<string, string> divide_ds(const string &s){ map<string, string> result; size_t p = 0; while(true){ size_t begin = s.find('{', p); if(begin == string::npos){ break; } string name = s.substr(p, begin - p); size_t end = s.find('}', begin); string code = s.substr(begin + 1, end - begin - 1); result.insert(make_pair(name, code)); p = end + 1; } return result; } vector<string> get_scripts(const Node &n){ vector<string> result; for(int i = 0; i < n.children.size(); ++i){ if(n.children[i].tag == "script"){ result.push_back(n.children[i].children[0].text); } } return result; } void apply_recur( const vector<string> &s, int ac, bool value, Node &n) { if(s[ac] == n.tag){ ++ac; } if(ac == s.size()){ n.visible = value; --ac; } for(int i = 0; i < n.children.size(); ++i){ apply_recur(s, ac, value, n.children[i]); } } void apply_script(const string &s, Node &n){ vector<string> expressions; { size_t p = 0; while(true){ size_t q = s.find(';', p); if(q == string::npos){ break; } expressions.push_back(s.substr(p, q - p)); p = q + 1; } } for(int i = 0; i < expressions.size(); ++i){ const string &expression = expressions[i]; vector<string> elements; size_t p = 0; while(true){ size_t q = expression.find('=', p); if(q == string::npos){ break; } elements.push_back(expression.substr(p, q - p)); p = q + 1; } elements.push_back(s.substr(p, s.size() - p)); bool value = (elements.back() == "true;"); for(int j = elements.size() - 2; j >= 0; --j){ string element = elements[j]; if(element[element.size() - 1] == '!'){ value = !value; element.resize(element.size() - 1); } vector<string> e; size_t a = 0; while(true){ size_t b = element.find('.', a); if(b == string::npos){ break; } e.push_back(element.substr(a, b - a)); a = b + 1; } apply_recur(e, 0, value, n); } } } struct Cell { char c; int type; // 0: none, 1: link, 2: button string text; Cell() : c('.'), type(0), text("") { } }; pii display_recur(vector< vector<Cell> > &area, Node &n, int x, int y){ int h = area.size(), w = area[0].size(); if(y >= h){ return pii(y, x); } if(!n.visible){ // nothing to do }else if(n.tag == ""){ const string &s = n.text; for(int i = 0; i < s.size(); ++i){ area[y][x].c = s[i]; if(++x >= w){ x = 0; if(++y >= h){ break; } } } }else if(n.tag == "br"){ x = 0; ++y; }else if(n.tag == "script"){ // nothing to do }else if(n.tag == "link"){ const string s = n.children[0].text; for(int i = 0; i < s.size(); ++i){ area[y][x].c = s[i]; area[y][x].type = 1; area[y][x].text = s; if(++x >= w){ x = 0; if(++y >= h){ break; } } } }else if(n.tag == "button"){ const string s = n.children[0].text; for(int i = 0; i < s.size(); ++i){ area[y][x].c = s[i]; area[y][x].type = 2; area[y][x].text = s; if(++x >= w){ x = 0; if(++y >= h){ break; } } } }else{ for(int i = 0; i < n.children.size(); ++i){ pii p = display_recur(area, n.children[i], x, y); x = p.second; y = p.first; } } return pii(y, x); } vector< vector<Cell> > display(int h, int w, Node &n){ vector< vector<Cell> > area(h, vector<Cell>(w)); display_recur(area, n, 0, 0); return area; } vector< vector<Cell> > display_file( int h, int w, const string &f, map<string, string> &fs) { Node n = parse_dml(fs[f + ".dml"]).n; return display(h, w, n); } int main(){ int N; cin >> N; map<string, string> files; string dummy; getline(cin, dummy); while(N--){ string name, data; getline(cin, name); getline(cin, data); files[name] = data; } int M; cin >> M; while(M--){ int w, h, s; string file; cin >> w >> h >> s >> file; Node n = parse_dml(files[file + ".dml"]).n; vector< vector<Cell> > area = display(h, w, n); while(s--){ int x, y; cin >> x >> y; const Cell &c = area[y][x]; if(c.type == 1){ // link n = parse_dml(files[c.text + ".dml"]).n; area = display(h, w, n); }else if(c.type == 2){ // button vector<string> scripts = get_scripts(n); for(int i = 0; i < scripts.size(); ++i){ map<string, string> ds = divide_ds(files[scripts[i] + ".ds"]); map<string, string>::iterator it = ds.find(c.text); if(it != ds.end()){ apply_script(it->second, n); } } area = display(h, w, n); } } for(int i = 0; i < h; ++i){ for(int j = 0; j < w; ++j){ cout << area[i][j].c; } cout << endl; } } return 0; }
#include <memory> #include <iostream> #include <sstream> #include <vector> #include <string> #include <map> #include <set> #include <algorithm> #include <stack> #include <queue> #include <deque> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <numeric> #include <complex> #include <cassert> #include <iterator> #include <functional> #if __cplusplus == 201103L #include <tuple> #endif using namespace std; #define REP(i,n) for(int i=0; i<(int)(n); ++i) struct Tag{ string name; string text; bool visible; vector<Tag*> child; Tag(string name) : name(name), visible(true) {} Tag(string name, string text) : name(name), text(text), visible(true) {} ~Tag(){ for(auto ch : child) delete ch; } }; typedef pair<Tag*, int> Result; Result parse_dml(const string& s, int p = 0){ assert(s[p++] == '<'); string tag_name; while(s[p] != '>'){ tag_name += s[p++]; } assert(s[p++] == '>'); Tag* tag = new Tag(tag_name); if(tag_name == "br") return Result(tag, p); while(s[p + 1] != '/'){ if(s[p] == '<'){ Result r = parse_dml(s, p); p = r.second; tag->child.push_back(r.first); }else{ string text; while(s[p] != '<'){ text += s[p++]; } tag->child.push_back( new Tag("", text) ); } } assert(s[p++] == '<'); assert(s[p++] == '/'); string tag_end; while(s[p] != '>') tag_end += s[p++]; assert(tag_name == tag_end); assert(s[p++] == '>'); return Result(tag, p); } void make_doc(Tag* p, Tag* doc[500][500], char view[500][500], int W, int H, int& x, int& y){ if(! p->visible) return; if(p->name == "script") return; if(p->name == "br"){ x = 0; y ++; return ; } for(auto np : p->child){ if(np->text.empty()){ make_doc(np, doc, view, W, H, x, y); }else{ for(auto c : np->text) { if(y < H) doc[y][x] = p; if(y < H) view[y][x] = c; if(x + 1 < W){ x++; }else{ x = 0; y++; } } } } } vector<string> collect_script(Tag* p, map<string, string>& file_dict){ vector<string> res; if(p->name == "script"){ assert(p->child[0]->text.size() > 0); string file = p->child[0]->text + ".ds"; res.push_back(file_dict[file]); return res; } for(auto np : p->child){ vector<string> vs = collect_script(np, file_dict); res.insert(res.end(), vs.begin(), vs.end()); } return res; } void apply(Tag* p, bool rval, vector<string>& selectors, int k){ if(p->name == selectors[k]) k++; if(k == (int)selectors.size() - 1) { p->visible = rval; }else{ for(auto np : p->child){ apply(np, rval, selectors, k); } } } void apply(Tag* root, string s){ vector<string> token; string cur; for(auto c : s){ if(cur == "=" || cur == "!=" || c == '!' || (cur != "!" && c == '=')) { token.push_back(cur); cur = ""; } cur += c; } token.push_back(cur); reverse(token.begin(), token.end()); bool expr = (token[0] == "true" ? true : false); for(int i = 2; i < (int)token.size(); i += 2){ assert(token[i - 1] == "=" || token[i - 1] == "!="); if(token[i - 1] == "!=") expr ^= expr; string t = token[i]; for(auto& c : t) if(c == '.') c = ' '; stringstream ss(t); vector<string> selectors; while(ss >> t) selectors.push_back(t); assert(selectors.size() >= 2); apply(root, expr, selectors, 0); } } void run(Tag* root, string func, map<string, string>& file_dict){ vector<string> scripts = collect_script(root, file_dict); for(string script : scripts){ for(auto& c : script) if(c == '{' || c == '}') c = ' '; stringstream ss(script); string name, program; while(ss >> name >> program) if(name == func){ for(auto& c : program) if(c == ';') c = ' '; stringstream ss(program); string sentence; while(ss >> sentence){ apply(root, sentence); } } } } int main(){ int N; cin >> N; map<string, string> file_dict; for(int i = 0; i < N; i++) { string name, data; cin >> name; cin.ignore(); getline(cin, data); file_dict[name] = data; } int M; cin >> M; while(M--){ int W, H, S; string file; cin >> W >> H >> S >> file; Tag* root = parse_dml(file_dict.at(file + ".dml")).first; Tag* doc[500][500] = {}; char view[500][500] = {}; int docx = 0, docy = 0; make_doc(root, doc, view, W, H, docx, docy); while(S--){ int x, y; cin >> x >> y; if(doc[y][x] && doc[y][x]->name == "link"){ assert(doc[y][x]->child.size() == 1); file = doc[y][x]->child[0]->text; delete root; root = parse_dml(file_dict.at(file + ".dml")).first; memset(doc, 0, sizeof(doc)); memset(view, 0, sizeof(view)); int docx = 0, docy = 0; make_doc(root, doc, view, W, H, docx, docy); }else if(doc[y][x] && doc[y][x]->name == "button"){ assert(doc[y][x]->child.size() == 1); string func = doc[y][x]->child[0]->text; run(root, func, file_dict); memset(doc, 0, sizeof(doc)); memset(view, 0, sizeof(view)); int docx = 0, docy = 0; make_doc(root, doc, view, W, H, docx, docy); } } for(int y = 0; y < H; y++){ for(int x = 0; x < W; x++){ if(view[y][x]) putchar(view[y][x]); else putchar('.'); } putchar('\n'); } } return 0; }
#include <bits/stdc++.h> using namespace std; #define dump(...) (cerr<<#__VA_ARGS__<<" = "<<(DUMP(),__VA_ARGS__).str()<<endl) struct DUMP : stringstream { template<class T> DUMP &operator,(const T &t) { if(this->tellp()) *this << ", "; *this << t; return *this; } }; constexpr double EPS = 1e-8; struct point { double x, y; point(double x_ = 0, double y_ = 0):x(x_), y(y_) {} point(const point &p):x(p.x), y(p.y) {} point operator+(const point &p) const { return point(x + p.x, y + p.y); } point operator-(const point &p) const { return point(x - p.x, y - p.y); } point operator*(double s) const { return point(x * s, y * s); } point operator*(const point &p) const { return point(x * p.x - y * p.y, x * p.y + y * p.x); } point operator/(const double s) const { return point(x / s, y / s); } bool operator<(const point &p) const { return x + EPS < p.x || (abs(x - p.x) < EPS && y + EPS < p.y); } bool operator==(const point &p) const { return abs(x - p.x) < EPS && abs(y - p.y) < EPS; } }; ostream &operator<<(ostream &os, const point &p) { return os << '(' << p.x << ", " << p.y << ')'; } point rotate90(const point &p) { return point(-p.y, p.x); } double norm(const point &p) { return p.x * p.x + p.y * p.y; } double abs(const point &p) { return sqrt(norm(p)); } double dot(const point &a, const point &b) { return a.x * b.x + a.y * b.y; } double cross(const point &a, const point &b) { return a.x * b.y - a.y * b.x; } struct line { point a, b; line(const point &a_, const point &b_):a(a_), b(b_) {} }; struct segment { point a, b; segment(const point &a_, const point &b_):a(a_), b(b_) {} }; struct circle { point c; double r; circle(const point &c_, double r_):c(c_), r(r_) {} }; double dist(const point &a, const point &b) { return abs(a - b); } double dist(const line &l, const point &p) { return abs(cross(l.b - l.a, p - l.a)) / abs(l.b - l.a); } double dist(const segment &s, const point &p) { if(dot(s.b - s.a, p - s.a) < 0) return dist(p, s.a); if(dot(s.a - s.b, p - s.b) < 0) return dist(p, s.b); return dist(line(s.a, s.b), p); } bool intersect(const circle &c, const point &p) { return dist(p, c.c) + EPS < c.r; } bool intersect(const circle &c, const segment &s) { return dist(s, c.c) + EPS < c.r; } point crosspoint(const line &a, const line &b) { const double tmp = cross(a.b - a.a, b.b - b.a); if(abs(tmp) < EPS) return a.a; return b.a + (b.b - b.a) * cross(a.b - a.a, a.a - b.a) / tmp; } vector<point> tangent(const circle &c, const point &p) { const double x = norm(p - c.c); double d = x - c.r * c.r; if(d < -EPS) return vector<point>(); d = max(d, 0.0); const point p1 = (p - c.c) * (c.r * c.r / x); const point p2 = rotate90((p - c.c) * (-c.r * sqrt(d) / x)); vector<point> res; res.push_back(c.c + p1 - p2); res.push_back(c.c + p1 + p2); return res; } constexpr double W = 50.0; constexpr double H = 94.0; constexpr double INF = INT_MAX; template<class T> inline void chmin(T &a, const T &b) { if(a > b) a = b; } bool out(const point &p) { return p.x < EPS || p.y < EPS || p.x + EPS > W || p.y + EPS > H; } vector<line> get_line(const circle &c, const point &p) { const auto ts = tangent(c, p); vector<line> res; for(const auto &t : ts) { if(t == p) { res.emplace_back(p, p + rotate90(c.c - p)); } else { res.emplace_back(p, t); } } return res; } int main() { const point start(W / 2.0, 0); const point goal(W / 2.0, H); cout.flags(ios::fixed); cout.precision(10); int N, D; cin >> N >> D; vector<circle> circles; circles.reserve(N); for(int i = 0; i < N; ++i) { int x, y, r; cin >> x >> y >> r; circles.emplace_back(point(x, y), r); } int cnt = 0; for(const auto &c : circles) { if(intersect(c, segment(start, goal))) ++cnt; } if(cnt <= D) { cout << 94.0 << endl; return 0; } vector<line> s_lines; vector<line> g_lines; s_lines.reserve(2 * N); g_lines.reserve(2 * N); for(const auto &c : circles) { auto ls = get_line(c, start); s_lines.insert(s_lines.end(), ls.begin(), ls.end()); ls = get_line(c, goal); g_lines.insert(g_lines.end(), ls.begin(), ls.end()); } double ans = INF; for(const auto &s_l : s_lines) { for(const auto &g_l : g_lines) { const point cp = crosspoint(s_l, g_l); if(out(cp)) continue; const segment s1(start, cp); const segment s2(cp, goal); cnt = 0; for(const auto &c : circles) { const bool i1 = intersect(c, s1); const bool i2 = intersect(c, s2); if(i1 && i2 && !intersect(c, cp)) { cnt += 2; } else if(i1 || i2) { ++cnt; } } if(cnt <= D) chmin(ans, dist(start, cp) + dist(cp, goal)); } } if(ans == INF) { puts("-1"); } else { cout << ans << endl; } return 0; }
#include<cstdio> #include<iostream> #include<vector> #include<complex> #include<string> #include<algorithm> #include<set> #include<cassert> using namespace std; #define reps(i,f,n) for(int i=f;i<int(n);i++) #define rep(i,n) reps(i,0,n) const double EPS = 1e-8; const double INF = 1e12; typedef complex<double> P; #define X real() #define Y imag() #define Curr(P,i) P[(i)%P.size()] #define Next(P,i) P[(i+1)%P.size()] #define Prev(P,i) P[(i+P.size()-1)%P.size()] namespace std{ bool operator<(const P a,const P b){ return a.X != b.X ? a.X < b.X : a.Y < b.Y; } } double cross(const P a,const P b){ return (conj(a)*b).imag(); } double dot(const P a,const P b){ return (conj(a)*b).real(); } // TODO make graph (20) int ccw(P a,P b,P c){ b-=a; c-=a; if(cross(b,c)>0) return +1;//counter clockwise if(cross(b,c)<0) return -1;//clockwise if(dot(b,c)<0) return +2;// c--a--b if(norm(b)<norm(c)) return -2;// a--b--c return 0;// a--c--b(or b==c) } struct L : public vector<P>{ L(const P a,const P b){ push_back(a),push_back(b); } }; typedef L S; typedef vector<P> G; struct C{ P p;double r; C(const P p,double r): p(p),r(r){} }; P projection(L a,P p){ double t = dot(p-a[0],a[0]-a[1])/norm(a[0]-a[1]+EPS); return a[0] + t*(a[0]-a[1]); } P reflection(L a,P p){ return p + 2.0 * (projection(a,p)-p); } bool isCrossLL(L a,L b){ return abs(cross(a[1]-a[0],b[1]-b[0])) > EPS || abs(cross(a[1]-a[0],b[0]-a[0])) < EPS ; } P crossP_LL(L a,L b){ double A = cross(a[1]-a[0],b[1]-b[0]); double B = cross(a[1]-a[0],a[1]-b[0]); if(abs(A)<EPS && abs(B)<EPS)return b[0]; if(abs(A)<EPS)assert(false); return b[0]+B/A*(b[1]-b[0]); } vector<L> TLine_CP(C c,P p){ P v = c.p - p; double t = asin(abs(c.r)/(abs(v))); P e = v/abs(v) * exp(P(.0,t)); P n1 = sqrt(abs(v)*abs(v) - c.r*c.r)*e + p; P n2 = reflection(L(p,c.p),n1); vector<L> ret; ret.push_back(L(p,n1)); ret.push_back(L(p,n2)); return ret; } bool isCrossSP(S a,P p){ return abs(a[0]-p)+abs(a[1]-p)-abs(a[0]-a[1]) < EPS; } double distSP(S a,P p){ const P r = projection(a,p); bool f = isCrossSP(a,r); return f ? abs(p-r) : min(abs(a[0]-p),abs(a[1]-p)); } double distPP(P a,P b){ return abs(a-b); } int n,m; vector<C> cir; void input(){ cin>>n>>m; rep(i,n){ int a,b,c; cin>>a>>b>>c; cir.push_back(C(P(a,b),c)); } } class Path : public vector<L>{ public: Path(L a){push_back(a);} Path(L a, L b){push_back(a);push_back(b);} }; vector<Path> path; void makeLines(){ P st(25,0); P en(25,94); path.push_back(Path(L(st,en))); rep(i,cir.size()){ rep(j,cir.size()){ vector<L> ps = TLine_CP(cir[i], st); vector<L> pe = TLine_CP(cir[j], en); rep(k,ps.size()){ rep(p,pe.size()){ path.push_back(Path(ps[k],pe[p])); } } } } } void printLines(){ rep(i,path.size()){ rep(j,path[i].size()){ printf("(%lf,%lf)-(%lf,%lf) ",path[i][j][0].X,path[i][j][0].Y,path[i][j][1].X,path[i][j][1].Y); }puts(""); } } bool boxin(P p){ return p.X>-EPS && p.X<50+EPS && p.Y>-EPS && p.Y<94+EPS; } void removeOut(){ rep(i,path.size()){ bool flg = true; rep(j,path[i].size()-1){ if(isCrossLL(path[i][j], path[i][j+1])){ P p = crossP_LL(path[i][j], path[i][j+1]); path[i][j][1] = p; path[i][j+1][1] = p; if(!boxin(p))flg=false; }else{ flg=false; } } if(!flg){ path.erase(path.begin()+i); i--; } } } void removeCircleOn(){ rep(i,path.size()){ int count = 0; rep(k,cir.size()){ rep(j,path[i].size()){ double dist = distSP(path[i][j], cir[k].p); if(dist+EPS<cir[k].r)count++; } if(distPP(cir[k].p, path[i][0][1])+EPS<cir[k].r)count--; } //printf("%d %d\n",i,count); if(count>m){ path.erase(path.begin()+i); i--; } } } /* 1 0 25 47 100 */ double minLength(){ double mini = INF; rep(i,path.size()){ double sum = 0; rep(j,path[i].size()){ sum += distPP(path[i][j][0], path[i][j][1]); } mini = min(sum, mini); } if(mini==INF)return -1; return mini; } double solve(){ makeLines(); removeOut(); //printLines(); removeCircleOn(); return minLength(); } int main(){ input(); printf("%.12lf\n",solve()); }
#include<bits/stdc++.h> using namespace std; const double EPS = 1e-8; const double INF = 1e12; typedef complex<double> P; #define X real() #define Y imag() #define Curr(P,i) P[(i)%P.size()] #define Next(P,i) P[(i+1)%P.size()] #define Prev(P,i) P[(i+P.size()-1)%P.size()] namespace std{ bool operator<(const P a,const P b){ return a.X != b.X ? a.X < b.X : a.Y < b.Y; } } double cross(const P a,const P b){ return (conj(a)*b).imag(); } double dot(const P a,const P b){ return (conj(a)*b).real(); } // TODO make graph (20) int ccw(P a,P b,P c){ b-=a; c-=a; if(cross(b,c)>0) return +1;//counter clockwise if(cross(b,c)<0) return -1;//clockwise if(dot(b,c)<0) return +2;// c--a--b if(norm(b)<norm(c)) return -2;// a--b--c return 0;// a--c--b(or b==c) } struct L : public vector<P>{ L(const P a,const P b){ push_back(a),push_back(b); } }; typedef L S; typedef vector<P> G; struct C{ P p;double r; C(const P p,double r): p(p),r(r){} }; //直線と点の関係 P projection(L a,P p){ double t = dot(p-a[0],a[0]-a[1])/norm(a[0]-a[1]); return a[0] + t*(a[0]-a[1]); } P reflection(L a,P p){ return p + 2.0 * (projection(a,p)-p); } //交差判定 //TODO CP(内包) CL CS (0) bool isCrossLL(L a,L b){ return abs(cross(a[1]-a[0],b[1]-b[0])) > EPS || abs(cross(a[1]-a[0],b[0]-a[0])) < EPS ; } bool isCrossLS(L a,S b){ return cross(a[1]-a[0],b[0]-a[0]) * cross(a[1]-a[0],b[1]-a[0]) < EPS; } bool isCrossLP(L l,P p){ return abs(cross(l[1]-p,l[0]-p)) < EPS; } bool isCrossSS(S a,S b){ return ccw(a[0],a[1],b[0]) * ccw(a[0],a[1],b[0]) <= 0 && ccw(b[0],b[1],a[0]) * ccw(b[0],b[1],a[0]) <= 0; } bool isCrossSP(S a,P p){ return abs(a[0]-p)+abs(a[1]-p)-abs(a[0]-a[1]) < EPS; } // 距離 CP CL CS は(distXP(x,c.p)-c.r) double distPP(P a,P b){ return abs(a-b); } double distLP(L a,P p){ return abs(p-projection(a,p)); } double distLL(L a,L b){ return isCrossLL(a,b) ? 0 : distLP(a,b[0]); } double distLS(L a,S b){ return isCrossLS(a,b) ? 0 : min(distLP(a,b[0]),distLP(a,b[1])); } double distSP(S a,P p){ const P r = projection(a,p); return isCrossSP(a,r) ? abs(p-r) : min(abs(a[0]-p),abs(a[1]-p)); } double distSS(S a,S b){ return isCrossSS(a,b)?0: min( min(distSP(a,b[0]),distSP(a,b[0])), min(distSP(a,b[0]),distSP(a,b[0])) ); } //円の交差判定 bool isCrossCP(C a,P p){ return abs(a.p-p)-a.r<=EPS; } bool isCrossCL(C a,L l){ return distLP(l,a.p)-a.r<EPS; } double distSP_MAX(S a,P p){ return max(abs(a[0]-p),abs(a[1]-p)); } bool isCrossCS(C a,S s){ return distSP(s,a.p)-a.r<-EPS&&distSP_MAX(s,a.p)-a.r>+EPS; } bool isCrossCC(C a,C b){//接してる時は交差 return abs(a.p-b.p)-(a.r+b.r) <= EPS; } //交差点 //先に交差判定をすること P crossP_LL(L a,L b){ double A = cross(a[1]-a[0],b[1]-b[0]); double B = cross(a[1]-a[0],a[1]-b[0]); if(abs(A)<EPS && abs(B)<EPS)return b[0]; if(abs(A)<EPS)assert(false); return b[0]+B/A*(b[1]-b[0]); } vector<P> crossP_CL(C c,L l){ P tmp = projection(l,c.p); P e = (l[0]-l[1])/abs(l[0]-l[1]); double h = abs(c.p-tmp)*abs(c.p-tmp); double t = sqrt(c.r*c.r - h*h); if(t<EPS)return {tmp}; return {tmp + e*t,tmp - e*t}; } vector<P> crossP_CC(C a,C b){ P A = conj(a.p-b.p); P B = (b.r*b.r - a.r*a.r - (b.p-a.p)*conj(b.p-a.p)); P C = a.r*a.r*(a.p-b.p); P D = B*B-4.0*A*C; P z1 = (-B+sqrt(D))/(2.0*A)+a.p; P z2 = (-B+sqrt(D))/(2.0*A)+b.p; return {z1,z2}; } //三点->円 P PPPtoC(P a,P b,P c){ P x = 1.0/(conj(b-a)); P y = 1.0/(conj(c-a)); return (y-x)/( conj(x)*y - x*conj(y) ) + a; } //凸包 G convex_hull(G ps){ int n = ps.size(); int k = 0; G ch(2*n); for(int i = 0;i<n;(ch[k++]=ps[i++])){ while(k>=2&&ccw(ch[k-2],ch[k-1],ps[i])<=0)--k; } for(int i = n-2,t=k+1 ; i>=0 ; ch[k++]=ps[i--]){ while(k>=t && ccw(ch[k-2],ch[k-1],ps[i])<=0)--k; } ch.resize(k-1); return ch; } //凸性判定 bool isConvex(G g){ for(int i=0; i<g.size();i++){ if(ccw(Prev(g,i),Curr(g,i),Next(g,i))>0)return false; } } //接線 //TODO check vector<L> TLine_CP(C c,P p){ P v = c.p - p; double t = asin(abs(c.r)/(abs(v))); P e = v/abs(v) * exp(P(.0,t)); P n1 = sqrt(abs(v)*abs(v) - c.r*c.r)*e + p; P n2 = reflection(L(p,c.p),n1); return {L(p,n1),L(p,n2)}; } // TLine CC vector<L> TLine_CPr(C c,P p,double r){ P v = c.p - p; double t = asin(abs(c.r)/(abs(v))); P e = v/abs(v) * exp(P(.0,t)); P n1 = sqrt(abs(v)*abs(v) - c.r*c.r)*e + p; P e1 = (n1-c.p)/abs(n1-c.p) * r; P n2 = reflection(L(p,c.p),n1); P e2 = (n2-c.p)/abs(n2-c.p) * r; return {L(p+e1,n1+e1),L(p+e2,n2+e2)}; } vector<L> TLine_CC(C a,C b){ //接してる時がヤバイ vector<L> res; if(!isCrossCC(a,b)&&(abs(a.r)>EPS)&&(abs(b.r>EPS))){ P tmp = (a.p-b.p)*(b.r)/(a.r+b.r) + b.p; auto t1 = TLine_CP(a,tmp); auto t2 = TLine_CP(b,tmp); res.push_back(L(t1[0][1],t2[0][1])); res.push_back(L(t1[1][1],t2[1][1])); } if(abs(a.r-b.r)<EPS){ const auto r = a.r; P e = (a.p-b.p)/abs(a.p-b.p) * exp(P(.0,90.0/180.0*M_PI)); res.push_back(L(a.p+(e*r),b.p+(e*r))); if(abs(r)>=EPS)res.push_back(L(a.p-(e*r),b.p-(e*r))); }else{ if(a.r<b.r)swap(a,b); auto t3 = TLine_CPr(C(a.p,a.r-b.r),b.p,b.r); for(auto i:t3){ res.push_back(i); } } return res; } int d; vector<C> in; void init(){ in.clear(); } int input(){ int n; cin>>n>>d; if(cin.eof())return false; for(int i=0;i<n;i++){ double x,y,r; cin>>x>>y>>r; in.push_back(C{P{x,y},r}); } return true; } bool inside(P a){ return -EPS<a.X&&a.X<50+EPS&&-EPS<a.Y&&a.Y<94+EPS; } double solve(){ vector<L> sl; vector<L> gl; const P s(25,0); const P g(25,94); for(int i=0;i<in.size();i++){ vector<L> tmp = TLine_CP(in[i],s); for(auto i:tmp){ sl.push_back(i); } } for(int i=0;i<in.size();i++){ vector<L> tmp = TLine_CP(in[i],g); for(auto i:tmp){ gl.push_back(i); } } double ans = INF; { int c = 0; for(auto i:in){ if(isCrossCS(i,L(s,g)))c++; } if(c<=d)ans= min(ans,distPP(s,g)); } for(auto i:sl){ for(auto j:gl){ if(!isCrossLL(i,j))continue; P tmp = crossP_LL(i,j); if(!inside(tmp))continue; pair<S,S> route(L(s,tmp),L(tmp,g)); int c = 0; for(auto i:in){ if(isCrossCS(i,route.first))c++; if(isCrossCS(i,route.second))c++; if(isCrossCP(i,tmp))c--; } if(c>d)continue; ans = min(distPP(route.first[0],route.first[1])+distPP(route.second[0],route.second[1]),ans); } } if(abs(ans-INF)<EPS)return -1; return ans; } int main(){ while(init(),input()){ cout<<fixed<<setprecision(10)<<solve()<<endl; } }
#include <cmath> #include <iostream> #include <algorithm> #include <vector> using namespace std; #define DEBUG(x) cerr << #x << " = " << x << endl typedef double D; const D EPS = 1e-8; struct P { D x, y; P(D x_, D y_) : x(x_), y(y_) { } P() { } }; struct C { P p; D r; C(P p_, D r_) : p(p_), r(r_) { } C() { } }; struct L { P a, b; L(P a_, P b_) : a(a_), b(b_) { } }; P operator +(P a, P b) { return P(a.x+b.x, a.y+b.y); } P operator -(P a, P b) { return P(a.x-b.x, a.y-b.y); } P operator *(P p, D s) { return P(p.x*s, p.y*s); } P vec(P from, P to) { return to - from; } D inp(P a, P b) { return a.x*b.x + a.y*b.y; } D outp(P a, P b) { return a.x*b.y - a.y*b.x; } D norm(P p) { return inp(p,p); } D abs(P p) { return sqrt(norm(p)); } P projection(L l, P p) { P a = vec(l.a, l.b); P b = vec(l.a, p); D t = inp(b, a) / norm(a); return l.a + a * t; } int sign(D a, D b = 0.0) { if(a < b - EPS) return -1; if(a > b + EPS) return +1; return 0; } int ccw(P a, P b, P c) { b = vec(a, b); c = vec(a, c); if(sign(outp(b, c)) > 0) return +1; if(sign(outp(b, c)) < 0) return -1; if(sign(inp(b, c)) < 0) return +2; if(norm(b) < norm(c)) return -2; return 0; } bool iSP(L s, P p) { return ccw(s.a, s.b, p) == 0; } P rot90(P p) { return P(-p.y, p.x); } D dSP(L s, P p) { P r = projection(s, p); if(iSP(s, r)) return abs(vec(p, r)); return min(abs(vec(p, s.a)), abs(vec(p, s.b))); } P cLL(L l, L m) { D d = outp(vec(m.a, m.b), vec(l.a, l.b)); return l.a + vec(l.a, l.b) * outp(vec(m.a, m.b), vec(l.a, m.b)) * (1.0 / d); } bool iSC(L s, C c) { return sign(dSP(s, c.p), c.r) < 0; } vector<P> tangentCP(C c, P p) { double x = norm(p - c.p); double d = x - c.r * c.r; if(sign(d) < 0) return vector<P>(); d = max(d, 0.0); P q1 = (p - c.p) * (c.r * c.r / x); P q2 = rot90((p - c.p) * (-c.r * sqrt(d) / x)); vector<P> ret; ret.push_back(c.p + q1 - q2); ret.push_back(c.p + q1 + q2); return ret; } const double gx[2] { 25.0, 25.0 }; const double gy[2] { 0.0, 94.0 }; int main() { cout.setf(ios::fixed); cout.precision(10); int N, D; cin >> N >> D; vector<C> cs(N); for(int i = 0; i < N; i++) { cin >> cs[i].p.x >> cs[i].p.y >> cs[i].r; } int k = 0; L l(P(gx[0], gy[0]), P(gx[1], gy[1])); for(int i = 0; i < N; i++) { if(iSC(l, cs[i])) k++; } if(k <= D) { // 曲がる必要がないとき cout << 94.0 << endl; } else { // 曲がる必要があるとき bool ok = false; double res = 1e9; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { vector<P> t1 = tangentCP(cs[i], P(gx[0], gy[0])); vector<P> t2 = tangentCP(cs[j], P(gx[1], gy[1])); for(int a = 0; a < 2; a++) for(int b = 0; b < 2; b++) { P s(gx[0], gy[0]); L l1(s, t1[a]); if(sign(abs(vec(t1[a], s))) == 0) { P p = rot90(vec(cs[i].p, s)); l1 = L(s, s + p); } P g(gx[1],gy[1]); L l2(g, t2[b]); if(sign(abs(vec(t2[b], g))) == 0) { P p = rot90(vec(cs[j].p, g)); l2 = L(g, g + p); } P cp = cLL(l1, l2); if(!(sign(0.0, cp.x) < 0 && sign(cp.x, 50.0) < 0 && sign(0.0, cp.y) < 0 && sign(cp.y, 94.0) < 0)) { continue; } l1 = L(P(gx[0], gy[0]), cp); l2 = L(P(gx[1], gy[1]), cp); int damage = 0; for(int k = 0; k < N; k++) { int x = (int)iSC(l1, cs[k]) + (int)iSC(l2, cs[k]); if(x == 1) { damage++; } else if(x == 2) { if(sign(abs(vec(cs[k].p, cp)), cs[k].r) < 0) { damage++; } else { damage+=2; } } } if(damage <= D) { ok = true; if(res > abs(l1.a - l1.b) + abs(l2.a - l2.b)) { res = abs(l1.a - l1.b) + abs(l2.a - l2.b); } } } } } if(ok) { cout << res << endl; } else { cout << "-1" << endl; } } }
#include <bits/stdc++.h> #define REP(i,n) for(int i=0; i<(int)(n); ++i) using namespace std; using namespace std; typedef complex<double> P; const double EPS = 1e-8; // 誤差を加味した符号判定 int sign(double a, double b = 0){ if(a - b > EPS) return +1; if(a - b < -EPS) return -1; return 0; } // 比較演算子 namespace std{ bool operator < (const P& a, const P& b) { return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b); } } // 内積・外積 double dot(P a, P b){ return real(conj(a) * b); } double cross(P a, P b){ return imag(conj(a) * b); } // OAとOBのなす符号付き角度 [-pi, pi] // example : (1, 0), (0, 1) -> pi/2 double angle(P a, P b){ return arg(conj(a) * b); } // aをc中心にb[rad]回転 // verify : not yet. P rotate(P a, double b, P c = P()){ return (a - c) * polar(1.0, b) + c; } // 直線ABに対する点Cの位置 int ccw(P a, P b, P c) { b -= a; c -= a; if (cross(b, c) > +EPS) return +1; // 反時計回り if (cross(b, c) < -EPS) return -1; // 時計回り if (dot(b, c) < 0) return +2; // c--a--b の順番で一直線上 if (norm(b) < norm(c)) return -2; // a--b--c の順番で一直線上 return 0; // 点が線分ab上にある } enum{ OUT, ON, IN }; struct L : public vector<P> { L(){} L(P a, P b) { push_back(a); push_back(b); } P vector() const { return back() - front(); } }; // 注意: 端点で交わったり直線が重なったりする場合も交差していると判定する // 二直線の平行判定 // verify : aoj0021 bool paralell(L l, L m){ return sign(cross(l.vector(), m.vector())) == 0; } // 二直線の同一判定 bool equalLL(L l, L m){ return sign(cross(l.vector(), m[0] - l[0])) == 0; } // 直線と点の交差判定 bool iLP(L l, P p) { // 直線lとl[0]からpへの直線が平行 return sign(cross(l.vector(), p - l[0])) == 0; } // 線分と点の交差判定(端点の処理に注意) // verify : aoj1279 bool iSP(L s, P p) { return ccw(s[0], s[1], p) == 0; } // 直線と線分の交差判定(線分が重なっている時に注意) bool iLS(L l, L s) { // 直線lについて、線分sの端点が異なる側にある return sign(cross(l.vector(), s[0] - l[0]) * cross(l.vector(), s[1] - l[0])) <= 0; } // 二つの線分の交差判定(線分が重なっている時や端点の処理に注意) bool iSS(L s, L t) { return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 && ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0; } // 点pから直線lに対する射影 P proj(L l, P p){ double t = dot(p - l[0], l.vector()) / norm(l.vector()); return l[0] + t * l.vector(); } // 点pの直線lに関する反射 P refl(L l, P p){ return 2.0 * proj(l, p) - p; } // 直線と点の距離 double dLP(L l, P p){ // return abs(p - projection(l, p)); return abs(cross(l.vector(), p - l[0])) / abs(l.vector()); } // 線分と点の距離 ( not verified !!! ) double dSP(L s, P p){ if(sign(dot(s.vector(), p - s[0])) <= 0) return abs(p - s[0]); if(sign(dot(-s.vector(), p - s[1])) <= 0) return abs(p - s[1]); return dLP(s, p); } // 直線と直線の距離 double dLL(L l, L m){ // 平行でないときは0, 平行のときは垂線の長さ return paralell(l, m) ? dLP(l, m[0]) : 0; } // 直線と線分の距離 double dLS(L l, L s){ if(iLS(l, s)) return 0; return min(dLP(l, s[0]), dLP(l, s[1])); } // 線分と線分の距離 double dSS(L s, L t){ if(iSS(s, t)) return 0; return min({dSP(s, t[0]), dSP(s, t[1]), dSP(t, s[0]), dSP(t, s[1])}); } // 直線と直線の交点 P pLL(L l, L m){ double A = cross(l.vector(), m.vector()); double B = cross(l.vector(), l[1] - m[0]); if(sign(A) == 0 && sign(B) == 0) return m[0]; // 二直線が重なっている if(sign(A) == 0) assert(false); // 直線が交わらない return m[0] + m.vector() * B / A; } typedef vector<P> Pol; // 反時計回りを仮定 // Polの要素へのアクセス P curr(const Pol& a, int x){ return a[x]; } P next(const Pol& a, int x){ return a[(x + 1) % a.size()]; } P prev(const Pol& a, int x){ return a[(x - 1 + a.size()) % a.size()]; } // 点が多角形のどこにあるのか判定する // verify : aoj0012 int contains(const Pol& A, P p){ // 点pから半直線をひき、辺と交差する回数を数える bool in = false; for(int i = 0; i < A.size(); i++){ P a = curr(A, i) - p; P b = next(A, i) - p; if(a.imag() > b.imag()) swap(a, b); // aからbの直線がy=0と交わり、その交点は原点の右側である if(a.imag() <= 0 && 0 < b.imag() && cross(a, b) < 0){ in = !in; } if(sign(cross(a, b)) == 0 && sign(dot(a, b)) <= 0) return ON; } return in ? IN : OUT; } // 多角形の面積 // verify : aoj0079 aoj1100 double area(const Pol& A) { double res = 0; for(int i = 0; i < A.size(); i++){ res += cross(curr(A, i), next(A, i)); } return abs(res) / 2.0; } // 凸包 Pol convex_hull(vector<P> ps) { int n = ps.size(), k = 0; sort(ps.begin(), ps.end()); vector<P> ch(2*n); for (int i = 0; i < n; ch[k++] = ps[i++]){ // lower-hull while (k >= 2 && ccw(ch[k-2], ch[k-1], ps[i]) <= 0) --k; } for (int i = n-2, t = k+1; i >= 0; ch[k++] = ps[i--]){ // upper-hull while (k >= t && ccw(ch[k-2], ch[k-1], ps[i]) <= 0) --k; } ch.resize(k-1); return ch; } bool is_convex(const Pol& A){ for(int i = 0; i < A.size(); i++){ if(ccw(prev(A, i), curr(A, i), next(A, i)) > 0) return false; } return true; } // 凸多角形の直線による切断。直線の左側だけ残す // verify : aoj1283 Pol convex_cut(const Pol& A, L l){ Pol B; for(int i = 0; i < A.size(); i++){ P a = curr(A, i), b = next(A, i); if(ccw(l[0], l[1], a) != -1) B.push_back(a); //Aが直線lの右側でない if(ccw(l[0], l[1], a) * ccw(l[0], l[1], b) < 0) B.push_back(pLL(l, L(a, b))); } return B; } // 垂直二等分線 // verify: maximamcup2013 D L bisector(P a, P b){ P mid = (a + b) / 2.0; P vec = (mid - a) * P(0.0, 1.0); return L(mid, mid + vec); } // 点集合psのうちs番目のボロノイ領域 // verify: maximamcup2013 D Pol voronoi_cell(Pol A, const vector<P>& ps, int s){ for(int i = 0; i < ps.size(); i++){ if(i != s) A = convex_cut(A, bisector(ps[s], ps[i])); } return A; } struct C { P p; double r; C() {} C(P p, double r) : p(p), r(r) { } }; // 円と点の内外判定 int contains(C c, P p){ double d = abs(c.p - p); if(sign(d - c.r) > 0) return OUT; if(sign(d - c.r) == 0) return ON; return IN; } // 円と線分の交差判定(境界を含む) // Verified: AOJ 0129 bool iCS(C c, L l){ int c1 = contains(c, l[0]); int c2 = contains(c, l[1]); if(c1 > c2) swap(c1, c2); // (OUT, OUT) (OUT, ON) (OUT, IN) (ON, ON) (ON, IN) (IN, IN) の6通り if(c1 == OUT && c2 == IN) return true; if(c1 == IN && c2 == IN) return false; if(c1 == ON) return true; // (接するとき) double d = dSP(l, c.p); if(sign(d - c.r) < 0) return true; if(sign(d - c.r) == 0) return true; // (接するとき) if(sign(d - c.r) > 0) return false; assert(false); } // 二つの円の交差判定(接する時を含む) bool iCC(C c, C d){ // 円の中心同士の距離が、半径の和以下であり、半径の差以上である double e = abs(d.p - d.p); return sign(e - (c.r + d.r)) <= 0 && sign(e - abs(c.r - d.r)) >= 0; } // 円と直線の交点 // verify : aoj2045 vector<P> pLC(L l, C c) { vector<P> res; P center = proj(l, c.p); double d = abs(center - c.p); double tt = c.r * c.r - d * d; if(tt < 0 && tt > -EPS) tt = 0; if(tt < 0) return res; double t = sqrt(tt); P vect = l.vector(); vect /= abs(vect); res.push_back(center - vect * t); if (t > EPS) { res.push_back(center + vect * t); } return res; } // 円と線分の交点 vector<P> pSC(L s, C c) { vector<P> ret; vector<P> nret = pLC(s, c); for (int i = 0; i < nret.size(); i++) { if (iSP(s, nret[i])) ret.push_back(nret[i]); } return ret; } // 円と円の交点 // verify : aoj1183 vector<P> pCC(C a, C b){ vector<P> res; double l = abs(b.p - a.p); if(sign(l) == 0 && sign(a.r - b.r) == 0) assert(false); // 解が無限に存在する if(sign(l - abs(a.r - b.r)) < 0 || sign(l - (a.r + b.r)) > 0) return res; // 解が存在しない double th1 = arg(b.p - a.p); if(sign(l - abs(a.r - b.r)) == 0 || sign(l - (a.r + b.r)) == 0){ res.push_back(a.p + polar(a.r, th1)); }else { double th2 = acos( (a.r * a.r - b.r * b.r + l * l) / (2 * a.r * l) ); res.push_back(a.p + polar(a.r, th1 - th2)); res.push_back(a.p + polar(a.r, th1 + th2)); } return res; } // 2点を通る半径rの円の中心 // verify : aoj1132 vector<P> touching_circle2(P a, P b, double r){ vector<P> res; double d = abs(b - a); if(d > 2 * r) return res; P mid = 0.5 * (a + b); P dir = polar(sqrt(r * r - d * d / 4), arg(b - a) + M_PI / 2); res.push_back(mid + dir); res.push_back(mid - dir); return res; } // 3点を通る円 C touching_circle3(P a, P b, P c){ // 2つの垂直二等分線の交点が円の中心 P mid_ab = (a + b) / 2.0; L bis_ab(mid_ab, (mid_ab - a) * P(0.0, 1.0)); P mid_bc = (b + c) / 2.0; L bis_bc(mid_bc, (mid_bc - b) * P(0.0, 1.0)); assert(!paralell(bis_ab, bis_bc)); P center = pLL(bis_ab, bis_bc); return C(center, abs(a - center)); } // 円と円の共通部分の面積を求める. // ref: nya3j double cc_area(C c1, C c2) { double d = abs(c1.p - c2.p); if (c1.r + c2.r < d + EPS) { return 0.0; } else if (d < abs(c1.r - c2.r) + EPS) { double r = min(c1.r, c2.r); // 元は c1.r >? c2.r だった. return r * r * M_PI; } else { double rc = (d*d + c1.r*c1.r - c2.r*c2.r) / (2*d); double theta = acos(rc / c1.r); double phi = acos((d - rc) / c2.r); return c1.r*c1.r*theta + c2.r*c2.r*phi - d*c1.r*sin(theta); } } // 円の接線 (中心から偏角thの点で接する接線) // verified: AOJ 2201 Immortal Jewels L circle_tangent(const C& c, double th){ P p0 = c.p + polar(c.r, th); P p1 = p0 + polar(1.0, th + M_PI / 2); return L(p0, p1); } // 二つの円の共通接線 (cの中心から接点へのベクトルの偏角を返す) // verified: AOJ 2201 Immortal Jewels // 参考: http://geom.web.fc2.com/geometry/circle-circle-tangent.html vector<double> common_tangents(const C& c, const C& d){ vector<double> res; P v = d.p - c.p; double l = abs(v); // 二円の中心間の距離 double a = arg(v); // 二円の中心間の偏角 if(sign(l - abs(c.r - d.r)) > 0){ // 交わる or 外接 or 離れている // 二つの外側接線 double a1 = acos((c.r - d.r) / l); res.push_back(a + a1); res.push_back(a - a1); if(sign(l - (c.r + d.r)) > 0){ // 離れている // 二つの内側接線 double a2 = acos((c.r + d.r) / l); res.push_back(a + a2); res.push_back(a - a2); } } if((sign(l - abs(c.r - d.r)) == 0 || sign(l - (c.r + d.r)) == 0) && sign(l) != 0){ // 内接 or 外接 // 一つの接線 res.push_back(a); } return res; } // 1点を通る円の接線( pがcの外側にあることが前提条件 ) // verified : AOJ 2579 vector<L> tangents_through_point(const C& c, const P& p){ vector<L> tangents; double d = abs(c.p - p); // d ^ 2 == r ^ 2 + e ^ 2 double e = sqrt(d * d - c.r * c.r); // 点pと円の接点の距離 // d * sin(th) = r double th = asin(c.r / d); P q1 = p + (c.p - p) * polar(1.0, +th) * e / d; P q2 = p + (c.p - p) * polar(1.0, -th) * e / d; tangents.push_back(L(p, q1)); tangents.push_back(L(p, q2)); return tangents; } // 三角形の内心 // verify : aoj 1301 P incenter(P p1, P p2, P p3){ double a = abs(p2 - p3); double b = abs(p3 - p1); double c = abs(p1 - p2); return (a * p1 + b * p2 + c * p3) / (a + b + c); } int main(){ const double W = 50; const double H = 94; int N, D; cin >> N >> D; vector<C> c(N); REP(i, N){ double x, y, r; cin >> x >> y >> r; c[i] = {{x, y}, r}; } const P start(W / 2, 0); const P goal (W / 2, H); vector<L> st, gt; for(int i = 0; i < N; i++){ vector<L> sv = tangents_through_point(c[i], start); vector<L> gv = tangents_through_point(c[i], goal ); st.insert(st.end(), sv.begin(), sv.end()); gt.insert(gt.end(), gv.begin(), gv.end()); } const double INF = 1e9; double ans = INF; // 直線で進んだとき { L shortest(start, goal); int cnt = 0; for(int i = 0; i < N; i++){ if(iCS(c[i], shortest)) cnt++; } if(cnt <= D){ ans = abs(shortest.vector()); } } // 円を接するときの経路 for(L sl : st){ for(L gl : gt){ if(paralell(sl, gl)) continue; P cp = pLL(sl, gl); if(!(sign(0, cp.real()) <= 0 && sign(cp.real() ,W) <= 0)) continue; if(!(sign(0, cp.imag()) <= 0 && sign(cp.imag(), H) <= 0)) continue; L sm(start, cp); L gm(cp, goal); // cout << sm[0] << " -> " << sm[1] << endl; // cout << gm[0] << " -> " << gm[1] << endl; int cnt = 0; for(int i = 0; i < N; i++){ if(iCS(c[i], sm) && sign(dSP(sm, c[i].p), c[i].r) != 0) cnt++; if(iCS(c[i], gm) && sign(dSP(gm, c[i].p), c[i].r) != 0) cnt++; if(contains(c[i], cp) == IN) cnt--; } if(cnt <= D){ double d = abs(sm.vector()) + abs(gm.vector()); ans = min(ans, d); } } } if(ans == INF) { printf("-1\n"); } else { printf("%.12f\n", ans); } return 0; }
#include<iostream> #include<cstdio> #include<complex> #include<vector> using namespace std; #define X real() #define Y imag() typedef long double D; typedef complex<D> P; struct L{P a, b;}; const D EPS = 1e-8; int sig(D a, D b = 0) {return a < b - EPS ? -1 : a > b + EPS ? 1 : 0;} bool near(P a, P b) {return !sig(norm(a - b));} namespace std { bool operator<(P a, P b) {return sig(a.X, b.X) ? a.X < b.X : a.Y < b.Y;} } D sr(D a) {return sqrt(max(a, (D)0));} D dot(P a, P b) {return a.X * b.X + a.Y * b.Y;} D det(P a, P b) {return a.X * b.Y - a.Y * b.X;} P vec(L a) {return a.b - a.a;} enum CCW{FRONT = 1, RIGHT = 2, BACK = 4, LEFT = 8, ON = 16}; int ccw(P a, P b, P c) { if (near(a, c) || near(b, c)) return ON; int s = sig(det(b - a, c - a)); if (s) return s > 0 ? LEFT : RIGHT; return (a < b) == (b < c) ? FRONT : (c < a) == (a < b) ? BACK : ON; } P proj(P a, P b) {return a * dot(a, b) / norm(a);} P perp(L l, P p) {return l.a + proj(vec(l), p - l.a);} bool iLLs(L a, L b) {return sig(det(vec(a), vec(b)));} P pLL(L a, L b) {return a.a + vec(a) * (det(vec(b), b.a - a.a) / det(vec(b), vec(a)));} D dLP(L l, P p) {return abs(det(vec(l), p - l.a) / vec(l));} D dSP(L s, P p) { if (dot(vec(s), p - s.a) < 0) return abs(p - s.a); if (dot(vec(s), p - s.b) > 0) return abs(p - s.b); return dLP(s, p); } struct C{P c; D r;}; bool iCSs(C c, L s) {return sig(c.r, dSP(s, c.c)) > 0;} pair<P, P> pCL(C c, L l) { P x = perp(l, c.c); P y = vec(l) / abs(vec(l)) * sr(c.r * c.r - norm(x - c.c)); return make_pair(x - y, x + y); } pair<P, P> tCP(C c, P p) { D d2 = norm(p - c.c); D x = sqrt(max(d2 - c.r * c.r, (D)0)); P h = c.c + (p - c.c) * (c.r * c.r / d2); P w = (p - c.c) * (x * c.r / d2) * P(0, 1); return make_pair(h - w, h + w); } #define rep(i, n) for (int i = 0; i < int(n); ++i) int main() { int n, d; cin >> n >> d; C c[n]; rep (i, n) { D x, y, r; cin >> x >> y >> r; c[i] = (C){P(x, y), r}; } L l; l.a = P(25, 0); l.b = P(25, 94); int cnt = 0; rep (i, n) if (iCSs(c[i], l)) ++cnt; if (cnt <= d) { puts("94"); return 0; } vector<L> vl1, vl2; rep (i, n) { pair<P, P> pp = tCP(c[i], l.a); vl1.push_back((L){l.a, pp.first}); vl1.push_back((L){l.a, pp.second}); } rep (i, n) { pair<P, P> pp = tCP(c[i], l.b); vl2.push_back((L){l.b, pp.first}); vl2.push_back((L){l.b, pp.second}); } D res = 1000; rep (i, vl1.size()) rep (j, vl2.size()) if (iLLs(vl1[i], vl2[j])) { P p = pLL(vl1[i], vl2[j]); if (sig(p.X) < 0 || sig(p.X, 50) > 0 || sig(p.Y) < 0 || sig(p.Y, 94) > 0) continue; cnt = 0; rep (i, n) if (iCSs(c[i], (L){l.a, p})) { pair<P, P> pp = pCL(c[i], (L){l.a, p}); if (ccw(l.a, p, pp.first) == ON) ++cnt; if (ccw(l.a, p, pp.second) == ON) ++cnt; } rep (i, n) if (iCSs(c[i], (L){l.b, p})) { pair<P, P> pp = pCL(c[i], (L){l.b, p}); if (ccw(l.b, p, pp.first) == ON) ++cnt; if (ccw(l.b, p, pp.second) == ON) ++cnt; } if (cnt / 2 <= d) { res = min(res, abs(l.a - p) + abs(l.b - p)); } } if (sig(res, 1000) == 0) { puts("-1"); } else { printf("%.12Lf\n", res); } }
#include<iostream> #include<complex> #include<vector> #include<algorithm> #include<cmath> #include<map> #include<iomanip> #include<cassert> #define EQ(a,b) (abs((a)-(b)) < EPS) #define fs first #define sc second #define pb push_back #define sz size() #define rep(i,n) for(int i=0;i<(int)(n);i++) #define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define all(a) (a).begin(),(a).end() using namespace std; typedef long double D; typedef complex<D> P; typedef pair<P,P> L; typedef pair<P,D> C; const D PI = acos(-1); const D EPS = 1e-10; P unit(P p){return p / abs(p);} pair<P,P> norm(P p){return make_pair(p*P(0,1),p*P(0,-1));} D dot(P x,P y){return real(conj(x)*y);} D cross(P x,P y){return imag(conj(x)*y);} bool para(L a,L b){return abs(cross(a.fs-a.sc,b.fs-b.sc))<EPS;} P line_cp(L a,L b){ return a.fs+(a.sc-a.fs)*cross(b.sc-b.fs,b.fs-a.fs)/cross(b.sc-b.fs,a.sc-a.fs); } D seg_p_dis(L a,P x){ if(dot(a.sc-a.fs,x-a.fs)<EPS)return abs(x-a.fs); if(dot(a.fs-a.sc,x-a.sc)<EPS)return abs(x-a.sc); return abs(cross(a.sc-a.fs,x-a.fs))/abs(a.sc-a.fs); } bool in_cir(C c,P x){return (abs(x-c.fs) +EPS < c.sc);} bool on_cir(C c,P x){return EQ(abs(x-c.fs),c.sc);} bool is_cp_cir_seg(C c, L s){ D dis = seg_p_dis(s, c.fs); return (dis+EPS<c.sc); } vector<P> cp_cir_to_line(C a, L l){ vector<P> v; P n = norm(l.fs-l.sc).fs; P p = line_cp(l,L(a.fs,a.fs+n)); if(on_cir(a,p))v.pb(p); else if(in_cir(a,p)){ D d = abs(a.fs-p); D len = sqrt(a.sc*a.sc - d*d); P cp_vec = len * unit(l.fs-l.sc); v.pb(p + cp_vec); v.pb(p - cp_vec); } return v; } vector<L> adj_line(C c, P p){ vector<L> res; P a = c.fs + c.sc * unit(c.fs-p); vector<P> b = cp_cir_to_line(C(c.fs,abs(c.fs-p)), L(a,a+norm(c.fs-p).fs)); rep(i,b.sz)res.pb(L(p, c.fs + c.sc * unit(c.fs-b[i]))); return res; } int main(){ int n,d; D x,y,r; C c[10]; cin >> n >> d; rep(i,n){ cin >> x >> y >> r; c[i] = C(P(x,y),r); } D res = -1.0; P s = P(25,0), g = P(25,94); L l = L(s,g); int cnt = 0; rep(i,n)cnt += is_cp_cir_seg(c[i],l); if(cnt <= d)res = abs(l.fs-l.sc); rep(i,n){ vector<L> v1 = adj_line(c[i],s); rep(j,n){ vector<L> v2 = adj_line(c[j],g); rep(ii,v1.sz)rep(jj,v2.sz){ if(para(v1[ii],v2[jj]))continue; P cp = line_cp(v1[ii],v2[jj]); if(cp.real()<EPS || cp.imag()<EPS || 50.0<cp.real()+EPS || 94.0<cp.imag()+EPS)continue; L l1 = L(s,cp), l2 = L(g,cp); cnt = 0; rep(k,n)cnt += is_cp_cir_seg(c[k],l1); rep(k,n)cnt += is_cp_cir_seg(c[k],l2); rep(k,n)if(in_cir(c[k],cp))cnt--; if(cnt <= d){ D dis = abs(l1.fs-l1.sc) + abs(l2.fs-l2.sc); if(res<0 || res>dis+EPS)res = dis; } } } } if(res<0)cout << (int)res << endl; else cout << fixed << setprecision(10) << res << endl; }
#include <bits/stdc++.h> #define REP(i,n) for(int i=0; i<(int)(n); ++i) using namespace std; typedef complex<double> Point; const double EPS = 1e-6; int sign(double a){ if(a > EPS) return 1; if(a < -EPS) return -1; return 0; } bool lt(double a, double b){ return sign(a - b) < 0; } double dot(Point a, Point b){ return real(conj(a) * b); } double cross(Point a, Point b){ return imag(conj(a) * b); } int ccw(Point a, Point b, Point c){ b -= a; c -= a; if(cross(b, c) > +EPS) return +1; if(cross(b, c) < -EPS) return -1; if(dot(b, c) < 0) return +2; if(norm(b) < norm(c)) return -2; return 0; } struct Line : public vector<Point> { Line(const Point& a, const Point& b){ push_back(a); push_back(b); } Point vector() const { return back() - front(); } }; bool paralell(Line l, Line m){ return sign(cross(l.vector(), m.vector())) == 0; } Point crosspointLL(Line l, Line m){ double A = cross(l.vector(), m.vector()); double B = cross(l.vector(), l[1] - m[0]); if(sign(A) == 0) assert(false); return m[0] + m.vector() * B / A; } struct Circle { Point p; double r; Circle() {} Circle(Point p_, double r_) : p(p_), r(r_) {} }; vector<Line> tangents_through_point(const Circle& C, const Point& p){ vector<Line> tangents; double d = abs(C.p - p); // d ^ 2 == r ^ 2 + e ^ 2 double e = sqrt(d * d - C.r * C.r); // 点pと円の接点の距離 // d * sin(th) = r double th = asin(C.r / d); Point q1 = p + (C.p - p) * polar(1.0, +th) * e / d; Point q2 = p + (C.p - p) * polar(1.0, -th) * e / d; tangents.push_back(Line(p, q1)); tangents.push_back(Line(p, q2)); return tangents; } bool intersectSP(Line s, Point p) { return ccw(s[0], s[1], p) == 0; } Point projection(Line l, Point p){ double t = dot(p - l[0], l.vector()) / norm(l.vector()); return l[0] + t * l.vector(); } double distanceSP(Line s, Point p){ Point r = projection(s, p); if(intersectSP(s, r)) return abs(r - p); // 垂線が線分に交わるとき return min(abs(s[0] - p), abs(s[1] - p)); } enum{ OUT, ON, IN }; int contains(const Circle& C, const Point& p){ double d = abs(C.p - p); if(sign(d - C.r) > 0) return OUT; if(sign(d - C.r) == 0) return ON; return IN; } bool intersectCS(const Circle& C, const Line& l){ int c1 = contains(C, l[0]); int c2 = contains(C, l[1]); if(c1 > c2) swap(c1, c2); if(c1 == OUT && c2 == IN) return true; if(c1 == IN && c2 == IN) return false; if(c1 == ON) return false; double d = distanceSP(l, C.p); if(sign(d - C.r) < 0) return true; if(sign(d - C.r) == 0) return false; if(sign(d - C.r) > 0) return false; } void print(Line l){ cout << l[0] << " -> " << l[1] << endl; } int main(){ const double W = 50; const double H = 94; int N, D; cin >> N >> D; vector<Circle> c(N); REP(i, N){ double x, y, r; cin >> x >> y >> r; c[i] = Circle(Point(x, y), r); } const Point start(W / 2, 0); const Point goal (W / 2, H); vector<Line> st, gt; for(int i = 0; i < N; i++){ vector<Line> sv = tangents_through_point(c[i], start); vector<Line> gv = tangents_through_point(c[i], goal ); st.insert(st.end(), sv.begin(), sv.end()); gt.insert(gt.end(), gv.begin(), gv.end()); } const double INF = 1e9; double ans = INF; Line shortest(start, goal); int cnt = 0; for(int i = 0; i < N; i++){ if(intersectCS(c[i], shortest)) cnt++; } if(cnt <= D){ ans = abs(shortest.vector()); } for(Line sl : st){ for(Line gl : gt){ if(paralell(sl, gl)) continue; Point cp = crosspointLL(sl, gl); if(!(lt(0, cp.real()) && lt(cp.real(), W))) continue; if(!(lt(0, cp.imag()) && lt(cp.imag(), H))) continue; Line sm(start, cp); Line gm(cp, goal); int cnt = 0; for(int i = 0; i < N; i++){ if(intersectCS(c[i], sm)) cnt++; if(intersectCS(c[i], gm)) cnt++; if(contains(c[i], cp) == IN) cnt--; } if(cnt <= D){ double d = abs(sm.vector()) + abs(gm.vector()); ans = min(ans, d); } } } if(ans == INF) { printf("-1\n"); } else { printf("%.12f\n", ans); } return 0; }