GVKun编程网logo

Planet Communcation Gym - 101466C (模拟+GCD)(space engine 模拟)

32

对于想了解PlanetCommuncationGym-101466C的读者,本文将提供新的信息,我们将详细介绍模拟+GCD,并且为您提供关于2017-2018ACM-ICPCLatinAmerican

对于想了解Planet Communcation Gym - 101466C 的读者,本文将提供新的信息,我们将详细介绍模拟+GCD,并且为您提供关于2017-2018 ACM-ICPC Latin American Regional Programming Contest GYM101889、Angular 2 Components Communicate、Angular material mat-icon 资源参考_Communication、applicationContext-common.xml]; nested exception is java.lang.NoClassDefFoundError: org/w3c/dom/E...的有价值信息。

本文目录一览:

Planet Communcation Gym - 101466C (模拟+GCD)(space engine 模拟)

Planet Communcation Gym - 101466C (模拟+GCD)(space engine 模拟)

 Lately the communication between planets has been an important issue,which is why the Earth has made many efforts to be connected to every other planet in the universe.

 The Universal Network Army of Lasers (UNAL) is trying to connect the Earth with other planets in the universe. In order to make this,the UNAL uses a laser machine which each time it is used,it sends a communication signal in the form of a ray of light in the direction of the planet.

 This laser machine is so powerful,that a ray of light generated by it is capable to cross all the planets it touches until the end of the universe. Moreover,when it fires a ray of light in one direction it also fires a ray of light in the opposite direction.

 Given the coordinates of all the planets in the universe,help the UNAL to design the way to communicate the Earth with all other planets in the universe using the machine the minimum number of times.

 

Input

 The first line of input contains one integer n (1 ≤ n ≤ 5000),the number of planets.

 The next n lines contains the list of coordinates of the planets. In particular,the i - th line contains three integers xiyizi ( - 109 ≤ xi, yi, zi ≤ 109),the coordinates of the i - th planet,respectively. The Earth is the first planet on the list. It is guaranteed that all the planets have different coordinates.

 

Output

 Output a single integer,the minimun number of times the machine should be used to communicate the Earth with all other planets in the universe

 

Examples

Input
3
0 0 0
1 1 0
-1 -1 0
Output
1

Input
4
0 0 0
1 0 0
0 1 0
0 0 1
Output
3
 
题意:
在三维空间给n个坐标,第一个坐标是地球的,问地球想对其他n-1个星球发射信号,最少需要发射多少个
说白了就是问n-1个星球与地球分别连线,求共线的有几条,总数减去共线的就是最少个数
 
思路:
用gcd将坐标化简,看有多少重复的,减掉就可以了
GCD,欧几里得算法,也称辗转相除法,用来求最大公倍数的不二算法
 
  1 #include <stdio.h>
  2 #include <string.h>
  3 
  4 struct node
  5 {
  6     long long a,b,c;
  7 } str[5005];
  8 
  9 long long vis[5005];
 10 
 11 long long gcd(long long a,long long b)   //低调奢华有内涵的gcd
 12 {
 13     if(b==0) return a;
 14     else return gcd(b,a%b);
 15 }
 16 
 17 int main()
 18 {
 19     long long n,i,j,x,m;
 20     long long a,c,eara,earb,earc;
 21     m = 0;
 22     scanf("%lld",&n);
 23     memset(vis,0,sizeof(vis));
 24     scanf("%lld %lld %lld",&eara,&earb,&earc);   //地球坐标
 25     n--;   //除去地球,n-1颗星球
 26     for(i=0; i<n; i++)
 27     {
 28         scanf("%lld %lld %lld",&a,&b,&c);
 29 
 30         a -= sa;   //相对地球的坐标
 31         b -= sb;
 32         c -= sc;
 33 
 34         if(a<0)     //反向也是共线,为了以后数据处理的方便,变个号,统一起来
 35         {
 36             a = -a;
 37             b = -b;
 38             c = -c;
 39         }
 40         if(a==0&&b==0)     //大粗长判断为的就是拿到最简坐标,0特殊考虑
 41         {
 42             str[i].a = str[i].b = 0;
 43             str[i].c = 1;
 44         }
 45         else if(b==0&&c==0)
 46         {
 47             str[i].b = str[i].c = 0;
 48             str[i].a = 1;
 49         }
 50         else if(a==0&&c==0)
 51         {
 52             str[i].a = str[i].c = 0;
 53             str[i].b = 1;
 54         }
 55         else if(a==0)
 56         {
 57             str[i].a = 0;
 58             x = gcd(b,c);
 59             str[i].b = b / x;
 60             str[i].c = c / x;
 61         }
 62         else if(b==0)
 63         {
 64             str[i].b = 0;
 65             x = gcd(a,c);
 66             str[i].a = a / x;
 67             str[i].c = c / x;
 68         }
 69         else if(c==0)
 70         {
 71             str[i].c = 0;
 72             x = gcd(a,b);
 73             str[i].a = a / x;
 74             str[i].b = b / x;
 75         }
 76         else
 77         {
 78             x = gcd(a,gcd(b,c));
 79             str[i].a = a/x;
 80             str[i].b = b/x;
 81             str[i].c = c/x;
 82         }
 83         
 84     }
 85 
 86     for(i=0; i<n; i++)    //看看最简坐标有多少重复出现的(即共线)
 87     {
 88         if(vis[i]==1) continue;    //vis为1是已经判断过的,对于这种思路来讲不写会答案错误
 89         vis[i] = 1;
 90         for(j=i; j<n; j++)
 91         {
 92             if(str[i].a==str[j].a&&str[i].b==str[j].b&&str[i].c==str[j].c&&vis[j]==0)
 93             {
 94                 vis[j] = 1;
 95                 m++;
 96             }
 97         }
 98     }
 99     
100     printf("%lld\n",n-m);
101     return 0;
102 }

2017-2018 ACM-ICPC Latin American Regional Programming Contest GYM101889

2017-2018 ACM-ICPC Latin American Regional Programming Contest GYM101889

挺有意思的一套题,题也没有啥毒瘤了,本来是队切的结果种种原因大家全挂机了。

只补了百人题,一共 7 个,其他的暂时先不补了,,也不会嘛 qwq

H:签到

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int a[18],b[18];
 4 int main(){
 5     cin>>a[1]>>a[2]>>a[3]>>b[1]>>b[2]>>b[3];
 6     int ans = 0;
 7     for(int i=1;i<=3;i++)
 8         ans+=max(0,b[i]-a[i]);
 9     cout<<ans<<endl;
10 }
View Code

C:按情况模拟一下,签到。当时队友因为这个题写炸了心态受到了影响然后我又不在 ((

#include <bits/stdc++.h>
using namespace std;
int k,n;
int a[100005];
int num[100005];
vector<int> vis[100005];
int main(){
    ios::sync_with_stdio(false);
    cin>>k>>n;
    int cnt = 0;
    int tmp = 0;//那一个超出k的数
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if(a[i]>k){
            cnt++;
            tmp = a[i];
        } else{
            num[a[i]]++;
        }
    }
    for(int i=1;i<=k;i++){
        vis[num[i]].push_back(i);
    }
    if(cnt>=2){
        cout<<"*"<<endl;
    } else if(cnt==1){
        if((n-1)%k==0&&vis[(n-1)/k].size()==k){
            cout<<-tmp<<endl;
        } else if(n%k==0&&vis[n/k-1].size()==1&&vis[n/k].size()==k-1){//
            cout<<-tmp<<'' ''<<"+"<<vis[n/k-1][0]<<endl;
        } else{
            cout<<"*"<<endl;
        }
    } else if(cnt==0){
        if((n+1)%k==0&&vis[(n+1)/k].size()==k-1&&vis[(n+1)/k-1].size()==1){
            cout<<"+"<<vis[(n+1)/k-1][0]<<endl;
        } else if((n-1)%k==0&&vis[(n-1)/k].size()==k-1&&vis[(n-1)/k+1].size()==1){
            cout<<-vis[(n-1)/k+1][0]<<endl;
        } else if(n%k==0&&vis[n/k].size()==k-2&&vis[n/k+1].size()==1&&vis[n/k-1].size()==1){
            cout<<-vis[n/k+1][0]<<'' ''<<"+"<<vis[n/k-1][0]<<endl;
        } else{
            cout<<"*"<<endl;
        }
    }
}
View Code

B: 签到题

题意:给你目标字符串,你每次可以输入一个字符,输入字符为元音是会在当前串会在输入后反转,求方案数。

样例三很明显了,两边的顺序是固定的,只考虑 中间 那一部分就好。特殊情况判一下

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 string s;
 4 bool yuanyin(char a){
 5     return a==''a''||a==''e''||a==''i''||a==''o''||a==''u'';
 6 }
 7 int main(){
 8     ios::sync_with_stdio(false);
 9     cin>>s;
10     int n = s.length();
11     int odd = 0,even = 0;//我不会别的英语了
12     for(int i=0;i<n;i++){
13         if(yuanyin(s[i]))
14             even++;
15         else
16             odd++;
17     }
18     if(even==n||odd==n){
19         cout<<1<<endl;
20     } else{
21         if(!yuanyin(s[0])){
22             cout<<0<<endl;
23         } else{
24             int tmp = 0;
25             int i=0;
26             for(;i<n;i++) {
27                 if (yuanyin(s[i]))
28                     tmp++;
29                 if (tmp == (even + 1) / 2) {
30                     break;
31                 }
32             }
33             int j=i+1;
34             for(;j<n;j++){
35                 if(yuanyin(s[j]))
36                     break;
37             }
38             cout<<j-i<<endl;
39         }
40     }
41 }
View Code

E:搜索题,可以利用数位 dp 的思想,唔数位 dp 我之前写过一篇博客所以这道题有了思路之后还是挺简单的。

题意:给你一个串和整数 n,包含数字和 ''?'',''?'' 可以用任意数替代但不能含前导 0,求能被 n 整除的最小串。

 1 #include <bits/stdc++.h>
 2 //为什么取余的运算优先级会比加减法高啊喂。。。
 3 using namespace std;
 4 int dp[1005][1005];
 5 string s;int n,l;
 6 bool flag = false;
 7 void dfs(int len,int mod,string ans){
 8     if(flag) return;
 9     if(len==l){
10         if(mod==0){
11             cout<<ans<<endl;
12             flag = true;
13         }
14         return;
15     }
16     if(dp[len][mod]) return;
17     if(s[len]==''?''){
18         for(int i=0;i<=9;i++){
19             if(flag) return;
20             if(len==0&&i==0) continue;
21             dfs(len+1,(i+(mod*10))%n,ans+char(i+''0''));
22         }
23     } else{
24         if(flag) return;
25         dfs(len+1,(s[len]-''0''+mod*10)%n,ans+s[len]);
26     }
27     dp[len][mod]=1;
28 }
29 int main(){
30     ios::sync_with_stdio(false);
31     cin>>s>>n;
32     l=s.length();
33     dfs(0,0,"");
34     if(!flag)
35         cout<<"*"<<endl;
36 }
View Code

J:简单数学题,一个字符串,R 代表能跳,P 代表不能,青蛙可以从任何地方跳,求能跳回原点的步数 n 的方案数,n 需要小于字符串长度。

很明显的 gcd,然后判断一下因数就可以。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int gcd(int x,int y){
 4     return y==0?x:gcd(y,x%y);
 5 }
 6 string s;
 7 bool vis[100005];
 8 int main(){
 9     ios::sync_with_stdio(false);
10     cin>>s;
11     int n = s.length();
12     for(int l=1;l<n;l++){
13         if(n%l==0){
14             for(int i=0;i<l;i++){
15                 //如果在>=l的位置有解那么<l的位置一定也有解
16                 int pos = i;
17                 while (pos<n&&s[pos]==''R''){
18                     pos+=l;
19                 }
20                 if(pos>=n){
21                     vis[l]=true;
22                 }
23             }
24         }
25     }
26     int ans = 0;
27     for(int i=1;i<n;i++){
28         if(vis[gcd(i,n)])
29             ans++;
30     }
31     cout<<ans<<endl;
32 }
View Code

I:次小生成树板子题,题意不说了很简单。很久没写过 LCA 的题了今天算是复习了一下。

对于给定的那条边,如果本来就在 MST 里,直接输出,如果不在,减去两点间的最长路径即可,最长路径和 LCA 的数组一起处理就可以。

  1 #include <bits/stdc++.h>
  2 using namespace std;
  3 const int N = 1e5+5;
  4 
  5 map<pair<int,int>,int>mt;
  6 
  7 int fa[N],ran[N];
  8 int find(int a){
  9     if(a==fa[a])return a;
 10     return fa[a]=find(fa[a]);
 11 }
 12 void unite(int x,int y){
 13     x = find(x);
 14     y = find(y);
 15     if(x==y) return;
 16     if(ran[x]<ran[y])fa[x]=y;
 17     else{
 18         fa[y]=x;
 19         if(ran[x]==ran[y])
 20             ran[x]++;
 21     }
 22 }
 23 bool same(int x,int y){
 24     return find(x)==find(y);
 25 }
 26 
 27 vector<int>g[N],val[N];
 28 int par[N][22],maxx[N][22],dep[N];
 29 void dfs(int v,int fa){
 30     for(int i=0;i<g[v].size();i++){
 31         int u = g[v][i];
 32         if(u==fa)
 33             continue;
 34         dep[u]=dep[v]+1;
 35         par[u][0]=v;
 36         maxx[u][0]=val[v][i];
 37         dfs(u,v);
 38     }
 39 }
 40 
 41 int lca_(int x,int y) {
 42     if (dep[x] > dep[y])
 43         swap(x, y);
 44     int tmp1 = mt[make_pair(x, y)];//
 45     int res = 0;
 46     for (int i = 20; i >= 0; i--){
 47         if (dep[y] - dep[x] >= (1 << i)) {
 48             res = max(res,maxx[y][i]);
 49             y = par[y][i];
 50         }
 51     }
 52     if(x==y)
 53         return tmp1-res;//多的长度
 54     //这两个一定在同一高度了
 55     for(int i=20;i>=0;i--) {
 56         if (par[x][i] == par[y][i])
 57             continue;
 58         else {
 59             res = max(res,maxx[x][i]);
 60             res = max(res,maxx[y][i]);
 61             x = par[x][i], y = par[y][i];
 62         }
 63     }
 64     res = max(res,maxx[x][0]);
 65     res = max(res,maxx[y][0]);
 66     return tmp1-res;
 67 }
 68 
 69 struct Edge{
 70     int from,to,cost;
 71     Edge(){}
 72     Edge(int from,int to,int cost):from(from),to(to),cost(cost){}
 73     bool operator <(const Edge &b)const {
 74         return cost<b.cost;
 75     }
 76 }edg[200005];
 77 
 78 int n,m,q,a,b,c;
 79 
 80 void init(){
 81     for(int j=1;(1<<j)<=n;j++){
 82         for(int i=1;i<=n;i++){
 83             par[i][j]=par[par[i][j-1]][j-1];
 84             maxx[i][j]=max(maxx[i][j-1],maxx[par[i][j-1]][j-1]);
 85         }
 86     }
 87 }
 88 
 89 int main(){
 90     ios::sync_with_stdio(false);
 91     for(int i=1;i<=100000;i++){
 92         fa[i]=i,ran[i]=0;
 93     }
 94     cin>>n>>m;
 95     for(int i=1;i<=m;i++){
 96         cin>>a>>b>>c;
 97         edg[i]=Edge(a,b,c);
 98         mt[make_pair(a,b)]=c;
 99         mt[make_pair(b,a)]=c;
100     }
101     sort(edg+1,edg+1+m);
102     int ans = 0;
103     for(int i=1;i<=m;i++){
104         int u = edg[i].from,v = edg[i].to,cost = edg[i].cost;
105         if(!same(u,v)){
106             unite(u,v);
107             ans+=cost;
108             g[u].push_back(v);
109             g[v].push_back(u);
110             val[u].push_back(cost);
111             val[v].push_back(cost);
112         }
113     }
114     dep[1]=1;dfs(1,1);
115     init();
116     //cout<<ans<<endl;
117     cin>>q;
118     while (q--){
119         cin>>a>>b;
120         if(par[a][0]==b||par[b][0]==a)//本来就在MST里
121             cout<<ans<<endl;
122         else{
123             cout<<ans+lca_(a,b)<<endl;
124         }
125     }
126 }
View Code

F:离散化 + 树状数组。因为我是先学的线段树所以对树状数组不太熟。。。但还是能写下来的 (((

思路:两个值都相同的先合并,然后按一维排序,另一维做最大上升子序列权值和。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int N = 100005;
 5 struct node{
 6     int a,b;
 7     ll cost;
 8 }p[N];
 9 int n,s[N*4];//离散化
10 map<pair<int,int>, ll> m;
11 vector<int> l[N*4];
12 ll c[N*4];
13 int lowbit(int k){ return k&-k;}
14 void update(int pos,ll num){
15     while (pos<=4*N){
16         c[pos]=max(c[pos],num);
17         pos+=lowbit(pos);
18     }
19 }
20 ll maxx(int pos){
21     ll s = 0;
22     while (pos>0){
23         s=max(s,c[pos]);
24         pos-=lowbit(pos);
25     }
26     return s;
27 }
28 int cmp(int a,int b){
29     return a>b;
30 }
31 int main(){
32     ios::sync_with_stdio(false);
33     cin>>n;
34     for(int i=1;i<=n;i++){
35         cin>>p[i].a>>p[i].b>>p[i].cost;
36         s[2*i]=p[i].a;
37         s[2*i-1]=p[i].b;
38     }
39     sort(s+1,s+2*n+1);
40     int cnt = unique(s+1,s+2*n+1)-s-1;
41     for(int i=1;i<=n;i++){
42         int a = lower_bound(s+1,s+1+cnt,p[i].a)-s;
43         int b = lower_bound(s+1,s+1+cnt,p[i].b)-s;
44         m[make_pair(a,b)]+=p[i].cost;
45         l[a].push_back(b);
46     }
47     for(int i=1;i<=cnt;i++){
48         sort(l[i].begin(),l[i].end(),cmp);
49         for(int j=0;j<l[i].size();j++){
50             int b = l[i][j];
51             ll tmp = maxx(b-1);
52             ll all = tmp+m[make_pair(i,b)];
53             update(b,all);
54         }
55     }
56     cout<<maxx(cnt)<<endl;
57 }
View Code

 

Angular 2 Components Communicate

Angular 2 Components Communicate

本文介绍的内容是组件通信的常用方式:@Input、@Output、@ViewChild、模板变量、MessageService、broadcaster (Angular 1.x $rootScope 中 $on、$broadcast ) 和 Pub - Sub 模式、RxJS Subject 存在的问题。

输入属性 (父组件 -> 子组件)

counter.component.ts

import { Component,Input } from '@angular/core';

@Component({
    selector: 'exe-counter',template: `
      <p>当前值: {{ count }}</p>
      <button (click)="increment()"> + </button>
      <button (click)="decrement()"> - </button>
    `
})
export class CounterComponent {
    @input() count: number = 0;

    increment() {
        this.count++;
    }

    decrement() {
        this.count--;
    }
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'exe-app',template: `
   <exe-counter [count]="initialCount"></exe-counter>
  `
})
export class AppComponent {
  initialCount: number = 5;
}

输出属性 (子组件 -> 父组件)

counter.component.ts

import { Component,Input,Output,EventEmitter } from '@angular/core';

@Component({
    selector: 'exe-counter',template: `
      <p>当前值: {{ count }}</p>
      <button (click)="increment()"> + </button>
      <button (click)="decrement()"> - </button>
    `
})
export class CounterComponent {
    @input() count: number = 0;

    @Output() change: EventEmitter<number> = new EventEmitter<number>();

    increment() {
        this.count++;
        this.change.emit(this.count);
    }

    decrement() {
        this.count--;
        this.change.emit(this.count);
    }
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'exe-app',template: `
   <p>{{changeMsg}}</p> 
   <exe-counter [count]="initialCount" 
    (change)="countChange($event)"></exe-counter>
  `
})
export class AppComponent {
  initialCount: number = 5;

  changeMsg: string;

  countChange(event: number) {
    this.changeMsg = `子组件change事件已触发,当前值是: ${event}`;
  }
}

模板变量

child.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'child-component',template: `I'm {{ name }}`
})

export class ChildComponent {
  public name: string;
}

parent.component.ts

import {Component,OnInit} from '@angular/core';
import {ChildComponent} from './child-component.ts';

@Component({
  selector: 'parent-component',template: `
    <child-component #child></child-component>
    <button (click)="child.name = childName">设置子组件名称</button>
  `
})

export class ParentComponent implements OnInit {
  
  private childName: string;
  
  constructor() { }

  ngOnInit() { 
    this.childName = 'child-component';
  }
}

@ViewChild 装饰器

child.component.ts

import { Component,OnInit } from '@angular/core';

@Component({
    selector: 'exe-child',template: `
      <p>Child Component</p>  
    `
})
export class ChildComponent {
    name: string = '';
}

app.component.ts

import { Component,ViewChild,AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'my-app',template: `
    <h4>Welcome to Angular World</h4>
    <exe-child></exe-child>
  `,})
export class AppComponent {

  @ViewChild(ChildComponent)
  childCmp: ChildComponent;

  ngAfterViewInit() {
    this.childCmp.name = 'child-component';
  }
}

使用 MessageService - 基于 RxJS Subject

message.service.ts

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessage() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

home.component.ts

import { Component } from '@angular/core';
import { MessageService } from './message.service';

@Component({
    selector: 'exe-home',template: `
    <div>
        <h1>Home</h1>
        <button (click)="sendMessage()">Send Message</button>
        <button (click)="clearMessage()">Clear Message</button>
    </div>`
})

export class HomeComponent {
    constructor(private messageService: MessageService) {}
    
    sendMessage(): void {
        this.messageService.sendMessage('Message from Home Component to App Component!');
    }

    clearMessage(): void {
        this.messageService.clearMessage();
    }
}

app.component.ts

import { Component,OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { MessageService } from './message.service';

@Component({
    selector: 'my-app',template: `
    <div>
       <div *ngIf="message">{{message.text}}</div>
       <exe-home></exe-home>
    </div>
    `
})

export class AppComponent implements OnDestroy {
    message: any;
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        this.subscription = this.messageService
                                  .getMessage().subscribe( message => { 
                                      this.message = message; 
                                 });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

使用 broadcaster - 基于 RxJS Subject

实现 Angular 1.x 中的 $rootScope 对象中 $on$broadcast 的功能。

broadcaster.ts

import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';

interface broadcastEvent {
  key: any;
  data?: any;
}

@Injectable()
export class broadcaster {
  private _eventBus: Subject<broadcastEvent>;

  constructor() {
    this._eventBus = new Subject<broadcastEvent>();
  }

  broadcast(key: any,data?: any) {
    this._eventBus.next({key,data});
  }

  on<T>(key: any): Observable<T> {
    return this._eventBus.asObservable()
      .filter(event => event.key === key)
      .map(event => <T>event.data);
  }
}

child.component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'child'
})
export class ChildComponent {
  constructor(private broadcaster: broadcaster) {}
  
  registerStringbroadcast() {
    this.broadcaster.on<string>('MyEvent')
      .subscribe(message => {
        ...
      });
  }

  emitStringbroadcast() {
    this.broadcaster.broadcast('MyEvent','some message');
  }
}

本文主要是介绍组件通讯的思路,提供的都是相对简单的示例。如果想深入了解,请参考 - angular.cn - component-communication。

我有话说

1.在实际开发中,我们也经常使用 Pub (发布) - Sub (订阅模式) 来实现模块之间的消息通讯。接下来我们看一下 Pub - Sub 的核心点:

  • 至少包含 subscribe() 和 publish() 两个方法,subscribe() 用于实现消息订阅,publish() 方法用于发布消息。

  • 支持订阅不同的消息类型,且对于任何一种消息类型都可以添加多个观察者。内部实现一般使用 key-value 结构进行消息类型和观察者列表的存储。

  • 订阅观察者后,最好返回一个对象或函数对象,用于取消订阅。

具体示例如下(详细信息,请参考 - Pub/Sub JavaScript Object):

var events = (function(){
  var topics = {};
  var hOP = topics.hasOwnProperty;

  return {
    subscribe: function(topic,listener) {
      // 如果topic类型不存在,则创建
      if(!hOP.call(topics,topic)) topics[topic] = [];
      
      // 添加listener
      var index = topics[topic].push(listener) -1;

      // 返回对象用于移除listener
      return {
        remove: function() {
          delete topics[topic][index];
        }
      };
    },publish: function(topic,info) {
      if(!hOP.call(topics,topic)) return;

      topics[topic].forEach(function(item) {
              item(info != undefined ? info : {});
      });
    }
  };
})();

使用示例:

var subscription = events.subscribe('/page/load',function(obj) {
    // 事件处理
});

events.publish('/page/load',{
    url: '/some/url/path' 
});

2.RxJS Subject 在使用中存在一个问题,就是如果某个 observer (观察者) 在执行的时候出现异常,却没有进行异常处理,那么就会影响到其它的观察者。解决该问题,最简单的方式就是为所有的观察者添加异常处理。具体问题如下:

const source = Rx.Observable.interval(1000);
const subject = new Rx.Subject();

const example = subject.map(x => {
    if (x === 1) {
        throw new Error('oops');
    }
    return x;
});
subject.subscribe(x => console.log('A',x));
example.subscribe(x => console.log('B',x));
subject.subscribe(x => console.log('C',x));

source.subscribe(subject);

以上代码运行后,控制台的输出结果:

A 0
B 0
C 0
A 1
Rx.min.js:74 Uncaught Error: oops

解决方案:

const source = Rx.Observable.interval(1000);
const subject = new Rx.Subject();

const example = subject.map(x => {
    if (x === 1) {
        throw new Error('oops');
    }
    return x;
});

subject.subscribe(
    x => console.log('A',x),error => console.log('A Error:' + error)
);
    
example.subscribe(
    x => console.log('B',error => console.log('B Error:' + error)
);

subject.subscribe(
    x => console.log('C',error => console.log('C Error:' + error)
);

source.subscribe(subject);

关于 RxJS Subject 的详细信息,请查看 - RxJS Subject。

Angular material mat-icon 资源参考_Communication

Angular material mat-icon 资源参考_Communication

Icon Icon Name mat-icon code
alternate_email alternate email icon <mat-icon>alternate_email</mat-icon>
business business icon <mat-icon> business</mat-icon>
call call icon <mat-icon> call</mat-icon>
call_end call end icon <mat-icon> call_end</mat-icon>
call_made call made icon <mat-icon> call_made</mat-icon>
call_merge call merge icon <mat-icon> call_merge</mat-icon>
call_missed call missed icon <mat-icon> call_missed</mat-icon>
call_missed_outgoing call missed outgoing icon <mat-icon> call_missed_outgoing</mat-icon>
call_received call received icon <mat-icon> call_received</mat-icon>
call_split call split icon <mat-icon> call_split</mat-icon>
cancel_presentation cancel presentation icon <mat-icon> cancel_presentation</mat-icon>
cell_wifi cell wifi icon <mat-icon> cell_wifi</mat-icon>
chat chat icon <mat-icon> chat</mat-icon>
chat_bubble chat bubble icon <mat-icon> chat_bubble</mat-icon>
chat_bubble_outline chat bubble outline icon <mat-icon> chat_bubble_outline</mat-icon>
clear_all clear all icon <mat-icon> clear_all</mat-icon>
comment comment icon <mat-icon> comment</mat-icon>
contact_mail contact mail icon <mat-icon> contact_mail</mat-icon>
contact_phone contact phone icon <mat-icon> contact_phone</mat-icon>
contacts contacts icon <mat-icon> contacts</mat-icon>
dialer_sip dialer sip icon <mat-icon> dialer_sip</mat-icon>
dialpad dialpad icon <mat-icon> dialpad</mat-icon>
domain_disabled domain disabled icon <mat-icon> domain_disabled</mat-icon>
email email icon <mat-icon> email</mat-icon>
forum forum icon <mat-icon> forum</mat-icon>
import_contacts import contacts icon <mat-icon> import_contacts</mat-icon>
import_export import export icon <mat-icon> import_export</mat-icon>
invert_colors_off invert colors off icon <mat-icon> invert_colors_off</mat-icon>
list_alt list alt icon <mat-icon> list_alt</mat-icon>
live_help live help icon <mat-icon> live_help</mat-icon>
location_off location off icon <mat-icon> location_off</mat-icon>
location_on location on icon <mat-icon> location_on</mat-icon>
mail_outline mail outline icon <mat-icon> mail_outline</mat-icon>
message message icon <mat-icon> message</mat-icon>
mobile_screen_share mobile screen share icon <mat-icon> mobile_screen_share</mat-icon>
no_sim no sim icon <mat-icon> no_sim</mat-icon>
pause_presentation pause presentation icon <mat-icon> pause_presentation</mat-icon>
phone phone icon <mat-icon> phone</mat-icon>
phonelink_erase phonelink erase icon <mat-icon> phonelink_erase</mat-icon>
phonelink_lock phonelink lock icon <mat-icon> phonelink_lock</mat-icon>
phonelink_ring phonelink ring icon <mat-icon> phonelink_ring</mat-icon>
phonelink_setup phonelink setup icon <mat-icon> phonelink_setup</mat-icon>
portable_wifi_off portable wifi off icon <mat-icon> portable_wifi_off</mat-icon>
present_to_all present to all icon <mat-icon> present_to_all</mat-icon>
ring_volume ring volume icon <mat-icon> ring_volume</mat-icon>
rss_feed rss feed icon <mat-icon> rss_feed</mat-icon>
screen_share screen share icon <mat-icon> screen_share</mat-icon>
sentiment_satisfied_alt sentiment satisfied alt icon <mat-icon> sentiment_satisfied_alt</mat-icon>
speaker_phone speaker phone icon <mat-icon> speaker_phone</mat-icon>
stay_current_landscape stay current landscape icon <mat-icon> stay_current_landscape</mat-icon>
stay_current_portrait stay current portrait icon <mat-icon> stay_current_portrait</mat-icon>
stay_primary_landscape stay primary landscape icon <mat-icon> stay_primary_landscape</mat-icon>
stay_primary_portrait stay primary portrait icon <mat-icon> stay_primary_portrait</mat-icon>
stop_screen_share stop screen share icon <mat-icon> stop_screen_share</mat-icon>
swap_calls swap calls icon <mat-icon> swap_calls</mat-icon>
textsms textsms icon <mat-icon> textsms</mat-icon>
unsubscribe unsubscribe icon <mat-icon> unsubscribe</mat-icon>
voicemail voicemail icon <mat-icon> voicemail</mat-icon>
vpn_key vpn key icon <mat-icon> vpn_key</mat-icon>

applicationContext-common.xml]; nested exception is java.lang.NoClassDefFoundError: org/w3c/dom/E...

applicationContext-common.xml]; nested exception is java.lang.NoClassDefFoundError: org/w3c/dom/E...

14:59:16,747 ERROR ContextLoader:350 - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from file [D:\eclipse\workspace_web\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\czyxyg_ws\WEB-INF\classes\applicationContext-common.xml]; nested exception is java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:414)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:614)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:515)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4973)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2944)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1208)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1688)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
at org.apache.xerces.parsers.AbstractDOMParser.startDocument(Unknown Source)
at org.apache.xerces.impl.xs.XMLSchemaValidator.startDocument(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.startDocument(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl.startEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.startDocumentParsing(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:429)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
... 22 more
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ElementTraversal
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
... 42 more

 

 

pom文件引入:

  • <dependency>
    <groupId>xml-apis</groupId>
    <artifactId>xml-apis</artifactId>
    <version>1.4.01</version>
    </dependency>

今天关于Planet Communcation Gym - 101466C 模拟+GCD的介绍到此结束,谢谢您的阅读,有关2017-2018 ACM-ICPC Latin American Regional Programming Contest GYM101889、Angular 2 Components Communicate、Angular material mat-icon 资源参考_Communication、applicationContext-common.xml]; nested exception is java.lang.NoClassDefFoundError: org/w3c/dom/E...等更多相关知识的信息可以在本站进行查询。

本文标签: